dpvm7231 2015-04-15 17:41
浏览 21
已采纳

为什么从当前程序包将结构传递给具有文字struct参数的函数与从另一个程序包传递的函数不同?

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.

  • 写回答

1条回答 默认 最新

  • dtqi87613 2015-04-15 18:23
    关注

    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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行