为什么要从当前包传递struct到函数的结构参数与另一个包的函数不同? [英] Why passing struct to function with literal struct parameter from current package differs from the same for function from another package?
问题描述
包主
$ b导入fmt
类型结构struct {
字段字符串
}
func Fn(arg struct {字符串}){
fmt.Println(arg)
}
func main(){
Fn(Struct {john})
}
但是这给了 main.go 只有函数调用的变化是 为什么将函数移动到另一个包会影响类型逻辑? 您需要导出您的结构字段: 然后改变调用来使用导出的字段: 从语言规范(特别是最后一句): 对于结构字面值,适用以下规则: This works perferctly: But this gives main.go sub/sub.go Only change in function call is that Why moving function to another package affects types logic? Links to the docs will be appreciated. You need to export your struct field: and then also change the call to use the exported field: From the language spec (specifically the last sentence): For struct literals the following rules apply:
这篇关于为什么要从当前包传递struct到函数的结构参数与另一个包的函数不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! ./main.go:12:不能在参数sub.Fn $ c中使用struct literal(类型Struct)作为类型struct {field string} $ c $:
$
$ 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)
}
字段的零值。
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
: package main
import "go_tests/sub"
type Struct struct {
field string
}
func main() {
sub.Fn(Struct{"john"})
}
package sub
import "fmt"
func Fn(arg struct{field string}) {
fmt.Println(arg)
}
Fn(Struct{"john"})
was replaced with sub.Fn(Struct{"john"})
. type Struct struct {
Field string
}
func Fn(arg struct{Field string}) {
fmt.Println(arg)
}