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

Why passing struct to function with literal struct parameter from current package differs from the same for function from another package?

这很有效:

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.