Exporting structs in go

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

Exporting structs in go

问题

我有一个包含几个结构体的文件:

type StructBase struct {
    // ... 很多字段
}

type Struct1 struct {
    StructBase
    // ... 很多字段
}

ImplementedStruct1 := &Struct1{
    name: "test",
    // ...
}

我了解在 Go 语言中,所有大写字母开头的变量名都可以从包中导出。所以自然而然地,ImplementedStruct1 是可以导出的。然而,出于某种原因,我得到了一个 ImplementedStruct1 unexpected 的错误。

我是否漏掉了什么,可以让我从该包中导出一个已实现的结构体对象?这段代码似乎与 Go 结构体的教程一致。如果这很明显,我很抱歉,我一直在搜索,而且对 Go 语言还很新。谢谢!

英文:

I have a file that has a few structs in it:

type StructBase struct {
       // ... lots of fields
}

type Struct1 struct {
       StructBase
       // ... lots of fields
}

ImplementedStruct1 := &Struct1{
      name: "test",
      // ...
}

I understand in Go that all capital letter variable names are exported from the package. So naturally ImplementedStruct1 is exported. However, for whatever reason I am getting an

ImplementedStruct1 unexpected.

Am I missing something here that will allow me to export an implemented struct object from this package? This code seems consistent with this tutorial on Go structs. I apologize if this is obvious, I have been searching and am still pretty new to Go. Thank you!

答案1

得分: 4

在包范围内,你不能使用短变量声明。你需要使用以下语法声明变量:

var ImplementedStruct1 = &Struct1{
      name: "test",
      // ...
}
英文:

You cannot use short variable declarations in the package scope. You will have to declare your variable with the following syntax:

var ImplementedStruct1 = &Struct1{
      name: "test",
      // ...
}

huangapple
  • 本文由 发表于 2017年3月10日 05:39:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/42705948.html
匿名

发表评论

匿名网友

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

确定