Go, how to import struct and fields of other packages?

huangapple go评论79阅读模式
英文:

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".

huangapple
  • 本文由 发表于 2021年10月15日 13:11:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/69580235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定