这个Golang结构中的第二对括号是什么?

时间:2016-11-01 23:08:00

标签: go struct syntax

interface MyInterface 
{
    public String doStuff();
}

@Component
public class Bean implements MyInterface
{
    boolean todo = false; // change me as needed

    // autowire implementations or create instances within this class as needed
    @Qualifier("implA")
    @Autowired
    MyInterface implA;

    @Qualifier("implB")
    @Autowired
    MyInterface implB;

    public String doStuff()
    {
        if (todo)
        {
            return implA.doStuff();
        }
        else
        {
            return implB.doStuff();
        }
    }   
}

这看起来像一个嵌入式字段sync.Mutex的结构,但我无法理解第二组括号。它编译并执行但是什么了?为什么make指令上的标签很重要(确实如此)和逗号?感谢...

2 个答案:

答案 0 :(得分:10)

您拥有的示例相当于:

expires

除了在您的示例中,您没有声明setInterval的类型,而是具有匿名结构。在您的示例中,与我的type Cache struct { sync.Mutex mapping map[string]string } cache := Cache{ mapping: make(map[string]string), } 类型相反,类型是整个

Cache

所以想到第二对大括号为

Cache

一部分。

struct { sync.Mutex mapping map[string]string } 是一个内置函数,与C cache := Cache{ mapping: make(map[string]string), } 类似,它都初始化一个填充了0'd值的数据结构,在Go的情况下,某些数据结构需要以这种方式初始化,其他的(大部分结构)自动初始化为0'd值。需要该字段,以便编译器现在为make为空calloc()

逗号是Go的格式的一部分,你可以在一行中cache.mapping全部,但是当字段的分配与开始和结束括号不同时,它需要一个逗号。

答案 1 :(得分:0)

这被称为" struct literal"或者一个"匿名结构"事实上,你是如何总是在Go中创建结构的,它可能不会立即显而易见,因为你可能习惯于为结构类型创建新的类型,以使它们更简洁一些。

整个结构定义实际上是Go中的一个类型,就像int[]bytestring一样。就像你能做的那样:

type NewType int
var a NewType = 5 // a is a NewType (which is based on an int)

或:

a := 5 // a is an int

并且两者都是看起来像int的不同类型,你也可以用结构做同样的事情:

// a is type NewType (which is a struct{}).
type NewType struct{
  A string
}
a := NewType{
  A: "test string",
}

// a is type struct{A string}
a := struct{
  A string
}{
  A: "test string",
}

类型名称(NewType)刚刚被结构本身的类型struct{A string}替换。请注意,它们不是用于比较或赋值的相同类型(别名),但它们共享相同的语义。

相关问题