从另一个包中访问一个结构体。

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

Accessing a strut from another package

问题

我有以下模块

package apack

type Something structs{
    a string
    b string
}

var FullList []Something

func Complete() []Something {
    FullList = append(FullList, Something{
                      a: 'first',
                      b: 'second'
               })
    return FullList
}

现在是以下的主要部分

import "something/apack"

func main() {
    re = apack.Complete()
    for _,s := range re {
        s1 := apack.Something(s)
        fmt.Println(s1)
    }
}

当我运行它时,我得到以下结果:

{first second}

但是如果我这样做

        fmt.Println(s1.a)

我会得到以下错误:

./main.go:70:19: s1.a undefined (type apack.Something has no field or method a)

是否可以访问来自另一个包的结构体?

我认为map应该可以工作,只是对于这种情况不确定。

谢谢

英文:

I have the following modules

package apack

type Something structs{
    a string
    b string
}

var FullList []Something

func Complete() []Something {
    FullList = append(FullList, Something{
                      a: 'first',
                      b: 'second'
               })
    return FullList
}

Now the following main

import "something/apack"

func main() {
    re = apack.Complete()
    for _,s := range re {
        s1 := apack.Something(s)
        fmt.Println(s1)
    }
}

when I run it I get the following:

{first second}

but if I do something like

        fmt.Println(s1.a)

I get the following error:

./main.go:70:19: s1.a undefined (type apack.Something has no field or method a)

Is it possible to be able to access structs from another package?

I think map should work, just unsure how for this case.

Thanks

答案1

得分: 2

是的,这是可能的,只需将您想要从其他包中访问的结构体字段导出即可:

type Something struct {
	A string
	b string
}

然后,您可以访问结构体的所有导出字段,所以在其他包的代码中,fmt.Println(s1.A) 现在可以工作,但 fmt.Println(s1.b) 将无法工作,因为 b 仍然是一个未导出的字段。

此外,这里 是来自 A Tour of Go(我也推荐整个教程)关于导出名称的一个非常简单的课程。

英文:

Yes it's possible, just make the fields of your struct (that you want to access from the other package) exported:

type Something struct {
	A string
	b string
}

Then you can access all the exported fields from the struct so fmt.Println(s1.A) in the other package code will now work, but fmt.Println(s1.b) will not work as b is still an unexported field.

Also, here is a very simple lesson from A Tour of Go (which I also recommend as a whole) about exported names.

huangapple
  • 本文由 发表于 2022年8月16日 06:41:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/73367083.html
匿名

发表评论

匿名网友

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

确定