英文:
Go, how to import struct and fields of other packages?
问题
我有一个问题,如果我尝试导出其他包的结构体,调用一个获取日期的方法,并使用struct.field
获取字段,它不起作用。
// main/other
package other
type Birthday struct {
Day string
}
func (b *Birthday) SetDay() {
b.Day = "10"
}
// main
package main
import "main/other"
func main() {
f := other.Birthday{}
f.SetDay()
fmt.Println(f.Day) // "",没有返回任何内容
}
但是当我将main
函数放在与结构体相同的文件中时,它就可以工作了。
英文:
i have the next problem, if I try to export a struct of other package, call a method of get Dates, and get the field with ( struct.field), it doesn´t work
//main/other
package other
type Birthday struct{
Day string
}
func (b *Birthday) SetDay(){
b.Day = "10"
}
//main
package main
import ("main/other")
func main(){
f := other.Birthday{}
f.SetDay()
fmt.Println(f.Day) // "" no return nothing
}
but when i use the func main in the same file of the struct, this ones works.
答案1
得分: 2
我刚刚在playground上测试了你的程序:
package main
import (
"fmt"
"play.ground/foo"
)
func main() {
f := foo.Birthday{}
f.SetDay()
fmt.Println(f.Day)
}
-- go.mod --
module play.ground
-- foo/foo.go --
package foo
type Birthday struct {
Day string
}
func (b *Birthday) SetDay() {
b.Day = "10"
}
它确实正常工作。
请确保首先运行go mod init yourProject
,详细说明在"教程:创建一个Go模块"中。
英文:
I just tested your program on playground:
package main
import (
"fmt"
"play.ground/foo"
)
func main() {
f := foo.Birthday{}
f.SetDay()
fmt.Println(f.Day)
}
-- go.mod --
module play.ground
-- foo/foo.go --
package foo
type Birthday struct {
Day string
}
func (b *Birthday) SetDay() {
b.Day = "10"
}
It does work just fine.
Make sure to go mod init yourProject
first; as detailed in "Tutorial: Create a Go module".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论