- 此问题在此处已有答案**:
Invoking struct function gives "cannot refer to unexported field or method"(2个答案)
昨天关门了。
尝试在Golang中创建适配器模式,不确定我做错了什么。我的客户。去显示错误
第一个月
main.go
package main
import (
"context"
"oms/consumer"
)
func main() {
ctx := context.Background()
consumer.Consumer(ctx)
}
consumer.go
package consumer
import (
"context"
"fmt"
"oms/broker"
)
func Consumer(ctx context.Context) {
broker.Execute()
}
client.go
package broker
import (
"oms/broker/exchange"
)
type Client struct {
broker exchange.Exchange
}
func (c *Client) SetBroker(broker exchange.Exchange) {
c.broker = broker
}
func (c *Client) placeOrder(id string, quantity, price int) {
// I am getting error here
c.broker.placeOrder(id, quantity, price)
}
broker.go
package broker
// create a Client and set its broker to Paytm
import (
"oms/broker/paytm"
)
func Execute() {
client := &Client{}
client.SetBroker(paytm.Paytm{ /* fields */ })
client.placeOrder("order1", 10, 100)
}
exchange.go
package exchange
type Exchange interface {
placeOrder(id string, quantity, price int)
}
paytm.go
package paytm
import "oms/broker/exchange"
type Paytm struct {
// fields
}
func (p Paytm) placeOrder(id string, quantity, price int) {
// implementation for Paytm's placeOrder method
}
1条答案
按热度按时间mjqavswn1#
您正试图从
broker
包调用未导出的方法。如果要从paytm
包外部调用该方法,则应在接口和方法中将其重命名为PlaceOrder
。有关导出/未导出字段和方法的更多信息,请参见以下网址:https://golangbyexample.com/exported-unexported-fields-struct-go/