golang研究所

Go结构体不能跨包写方法

2020-04-07  本文已影响0人  百里江山

遇到如下错误: cannot define new methods on non-local type a.Show
意思是: 不能定义非本地类型的方法

实验一下

新建a和b两个文件夹.再分别新建2个文件a.go , b.go

a/a.go

package a
type Student struct {
    Name String
}

b/b.go

package b 
func (s a.Student) Show() {
    fmt.Println(s.Name)
}

main.go

func main() {
    student := new(a.Student)
    student.Name = "百里"
    student.Show() // (1) 会报错的.
}
上一篇 下一篇

猜你喜欢

热点阅读