繁体   English   中英

在 Golang SDK 中获取 Azure 位置列表的问题

[英]Problems with getting list of locations of Azure in Golang SDK

为什么在请求获取 Azure 的列表位置时收到“nil”?

例子:

import (
    "fmt"
    "context"
    "errors"
    "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-06-01/subscriptions"
)

func GetLocations(sess *AzureSession) (subscriptions.LocationListResult, error) {

    var locationsList subscriptions.LocationListResult

    client := subscriptions.NewClient()
    client.Authorizer = sess.Authorizer
    if locationsList, err := client.ListLocations(context.Background(), sess.SubscriptionID) ; err != nil {
        return locationsList, errors.New("Got error while traverising Azure locations")
    }

    fmt.Println(locationsList)

    return locationsList, nil
}

我做错了什么? 为什么我有回应:

{{<nil>} <nil>}

或者如何以其他方式获得此列表?

您在错误 if 块中使用了短变量声明:= 此运算符将自动检测变量的类型。 所以你不需要隐式输入它。 查看 golang 导览部分https://tour.golang.org/basics/10

解决方案删除隐式变量声明

...
func GetLocations(sess *AzureSession) (subscriptions.LocationListResult, error) {
    client := subscriptions.NewClient()
    client.Authorizer = sess.Authorizer
    if locationsList, err := client.ListLocations(context.Background(), sess.SubscriptionID) ; err != nil {
        return locationsList, errors.New("Got error while traverising Azure locations")
    }

    fmt.Println(locationsList)

    return locationsList, nil
}

解决方案删除短声明运算符

如果您真的想弄清楚 var 是哪种类型,请使用此代码段。

...
func GetLocations(sess *AzureSession) (subscriptions.LocationListResult, error) {

    var locationsList subscriptions.LocationListResult
    var err error

    client := subscriptions.NewClient()
    client.Authorizer = sess.Authorizer
    if locationsList, err = client.ListLocations(context.Background(), sess.SubscriptionID) ; err != nil {
        return locationsList, errors.New("Got error while traverising Azure locations")
    }

    fmt.Println(locationsList)

    return locationsList, nil
}

不能将短声明与隐式声明混合使用,这一点很重要。 因此,您还需要隐式声明err变量。

您正在获取位置指针,因此您应该在迭代 location.value 时使用位置指针,然后它将起作用。 在迭代时尝试以下格式

for _, location := range *locationsList.Value {
            listOfRegions = append(listOfRegions, *location.Name)
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM