Golang cannot take the address of

衣舞晨風發表於2018-02-06

今天在使用kubernetes/apimachinery下/pkg/api/resource中的Quantity接收k8s資源資訊的時候,報出如下錯誤:

..\server\handlers\adapter.go:70: 
cannot call pointer method on clusterQuota.Hard[admin.ResourceRequestsCPU]
..\server\handlers\adapter.go:70: 
cannot take the address of clusterQuota.Hard[admin.ResourceRequestsCPU]

具體出錯程式碼如下:

test:= clusterQuota.Hard[admin.ResourceRequestsCPU].Value()
fmt.Println(test)

Quantity結構及Value()方法如下:

type Quantity struct {
    // i is the quantity in int64 scaled form, if d.Dec == nil
    i int64Amount
    // d is the quantity in inf.Dec form if d.Dec != nil
    d infDecAmount
    // s is the generated value of this quantity to avoid recalculation
    s string

    // Change Format at will. See the comment for Canonicalize for
    // more details.
    Format
}
// Value returns the value of q; any fractional part will be lost.
func (q *Quantity) Value() int64 {
    return q.ScaledValue(0)
}

既然呼叫方法指定的是指標,那麼這麼呼叫是否可以?

ii := (&clusterQuota.Hard[tenant_admin.ResourceRequestsCPU]).Value()
fmt.Println(ii)

編譯發現還是不行,那應該怎麼處理呢?
其實會發現,取出變數的地址,需要兩步:

hardRequestCpu := clusterQuota.Hard[tenant_admin.ResourceRequestsCPU]
fmt.Println((&hardRequestCpu).Value())

本文參考:
https://stackoverflow.com/questions/10535743/address-of-a-temporary-in-go

個人微信公眾號:
這裡寫圖片描述

作者:jiankunking 出處:http://blog.csdn.net/jiankunking

相關文章