gpt4 book ai didi

types - struct{int} 和 struct{int int} 有什么区别?

转载 作者:IT王子 更新时间:2023-10-29 01:24:44 28 4
gpt4 key购买 nike

这两个结构除了不被认为是等效的之外还有什么区别?

package main
import "fmt"
func main() {
a := struct{int}{1}
b := struct{int int}{1}
fmt.Println(a,b)
a.int=2
b.int=a.int
fmt.Println(a,b)
//a = b
}

它们看起来一样:

$ go run a.go 
{1} {1}
{2} {2}

但是如果你取消注释 a = b,它会说:

$ go run a.go 
# command-line-arguments
./a.go:10: cannot use b (type struct { int int }) as type struct { int } in assignment

但是 struct{a,b int}struct{a int;b int} 是等价的:

package main

func main() {
a := struct{a,b int}{1,2}
b := struct{a int;b int}{1,2}
a = b
b = a
}

?

最佳答案

struct { int } 是一个带有 int 类型匿名字段的结构。

struct { int int } 是一个结构,其字段名为 int,类型为 int

int 不是关键字;它可以用作标识符。

结构类型不相同;相应的字段没有相同的名称。

用类型声明但没有显式字段名的字段是匿名字段,非限定类型名充当匿名字段名。因此,字段名称a.intb.int 是有效的。例如,

a := struct{ int }{1}
b := struct{ int int }{1}
a.int = 2
b.int = a.int

The Go Programming Language Specification

Struct types

A struct is a sequence of named elements, called fields, each of which has a name and a type. Field names may be specified explicitly (IdentifierList) or implicitly (AnonymousField). Within a struct, non-blank field names must be unique.

StructType     = "struct" "{" { FieldDecl ";" } "}" .
FieldDecl = (IdentifierList Type | AnonymousField) [ Tag ] .
AnonymousField = [ "*" ] TypeName .

A field declared with a type but no explicit field name is an anonymous field, also called an embedded field or an embedding of the type in the struct. An embedded type must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type. The unqualified type name acts as the field name.

Keywords

The following keywords are reserved and may not be used as identifiers.

break        default      func         interface    select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var

Type identity

Two struct types are identical if they have the same sequence of fields, and if corresponding fields have the same names, and identical types, and identical tags. Two anonymous fields are considered to have the same name. Lower-case field names from different packages are always different.

关于types - struct{int} 和 struct{int int} 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25515653/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com