struct - 为什么将结构传递给当前包中带有文字结构参数的函数不同于另一个包中的函数?

标签 struct go

这很有效:

package main

import "fmt"

type Struct struct {
    field string
}
func Fn(arg struct{field string}) {
    fmt.Println(arg)
}

func main() {
    Fn(Struct{"john"})
}

但这给出了 ./main.go:12: cannot use Struct literal (type Struct) as type struct { field string } in argument to sub.Fn:

main.go

package main

import "go_tests/sub"

type Struct struct {
    field string
}

func main() {
    sub.Fn(Struct{"john"})
}

sub/sub.go

package sub

import "fmt"

func Fn(arg struct{field string}) {
    fmt.Println(arg)
}

函数调用的唯一变化是 Fn(Struct{"john"}) 被替换为 sub.Fn(Struct{"john"})

为什么将函数移动到另一个包会影响类型逻辑?链接到文档将不胜感激。

最佳答案

您需要导出您的结构字段:

type Struct struct {
    Field string
}

然后还更改调用以使用导出的字段:

func Fn(arg struct{Field string}) {
    fmt.Println(arg)
}

来自language spec (特别是最后一句):

For struct literals the following rules apply:

  • A key must be a field name declared in the LiteralType.
  • An element list that does not contain any keys must list an element for each struct field in the order in which the fields are declared.
  • If any element has a key, every element must have a key.
  • An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.
  • A literal may omit the element list; such a literal evaluates to the zero value for its type.
  • It is an error to specify an element for a non-exported field of a struct belonging to a different package.

关于struct - 为什么将结构传递给当前包中带有文字结构参数的函数不同于另一个包中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29657109/

相关文章:

swift - 在 Swift 3 中从数据初始化结构

go - 如何覆盖默认的 404 未找到处理程序?

go - net/rpc .Call 与 .Go 之间有什么区别?

sql - Goland 可以使用其他 SQL 包自动完成 SQL 语句吗?

从接口(interface)获取指向结构的指针?

c# - 使答案类成为结构?

c - 使用 struct 和 switch 的意外循环

arrays - 结构体数组 : How to save in coredata?

go - 函数无法识别 Yaml 嵌套结构

c - 全局修改数组/结构不起作用