猿问

为什么不去投射 0 到 *int32?

我觉得这是一个非常简单的代码,但它似乎不起作用。


我有一个API给我的结构:


// Count - Number of agents (VMs) to host docker containers. Allowed values must be in the range of 0 to 100 (inclusive) for user pools and in the range of 1 to 100 (inclusive) for system pools. The default value is 1.

Count *int32 `json:"count,omitempty"`

但是当我尝试创建它时,如下所示:


agentPoolProfile := containerservice.ManagedClusterAgentPoolProfileProperties{

    Count: int32(0)}

我收到以下错误:


cannot use int32(0) (constant 0 of type int32) as *int32 value in struct literal

我敢肯定,对于那些熟悉go的人来说,这是一个1秒的修复程序。但是:a)为什么在结构中铸造不起作用?b) “*”在这个结构中做什么?c)这是惯用语吗?那就是 - 我应该只写所有的值,如?agentPoolProfile.Count = *int32(0)


互换的青春
浏览 111回答 1
1回答

肥皂起泡泡

指向 int32 的指针需要有一个指向的内存地址,而文本 0 没有该地址。您需要以某种方式创建一个具有值的实变量,以便该值实际上存在于某个地方的内存中,然后您可以使用其地址。编写一个帮助程序函数是很常见的,它将按照我上面描述的那样做:// Int32 returns a pointer to the int32 value passed in.func Int32(v int32) *int32 {    return &v}
随时随地看视频慕课网APP

相关分类

Go
我要回答