为什么要从当前包传递struct到函数的结构参数与另一个包的函数不同? [英] Why passing struct to function with literal struct parameter from current package differs from the same for function from another package?

查看:141
本文介绍了为什么要从当前包传递struct到函数的结构参数与另一个包的函数不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 包主
$ b导入fmt

类型结构struct {
字段字符串
}
func Fn(arg struct {字符串}){
fmt.Println(arg)
}

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

但是这给了 ./main.go:12:不能在参数sub.Fn

main.go

  $ 





$ struct $ {



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



/ sub>

 包子

importfmt

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

只有函数调用的变化是 Fn(Struct {john})被替换ced with sub.Fn(Struct {john})

为什么将函数移动到另一个包会影响类型逻辑?

解决方案

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

 类型结构struct {
字段字符串
}

然后改变调用来使用导出的字段:

  func Fn(arg struct {字段字符串}){
fmt.Println(arg)
}

语言规范(特别是最后一句):


对于结构字面值,适用以下规则:


  • 键必须是在LiteralType。
  • 不包含任何键的元素列表必须按每个结构字段的声明顺序列出一个元素。

  • 如果任何元素有一个键,则每个元素都必须有一个键。
  • 包含键的元素列表不包含n不需要为每个结构字段设置一个元素。省略字段将获得该
    字段的零值。
  • 文字可以省略元素列表;这样的文字评估为其类型的零值。

  • 为属于不同包的结构的非导出字段指定元素是错误的。



This works perferctly:

package main

import "fmt"

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

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

But this gives ./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)
}

Only change in function call is that Fn(Struct{"john"}) was replaced with sub.Fn(Struct{"john"}).

Why moving function to another package affects types logic? Links to the docs will be appreciated.

解决方案

You need to export your struct field:

type Struct struct {
    Field string
}

and then also change the call to use the exported field:

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

From the language spec (specifically the last sentence):

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到函数的结构参数与另一个包的函数不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆