登录
首页 >  Golang >  Go问答

未使用额外变量,无法对数组进行索引

来源:stackoverflow

时间:2024-02-17 21:45:25 420浏览 收藏

本篇文章给大家分享《未使用额外变量,无法对数组进行索引》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我认为理论上我在传递引用主题中错过了一些东西,但我无法找到一种方法来读取 id 而不使用支持 networkinterfacereference

package main

import (
    "context"
    "fmt"

    "github.com/azure/azure-sdk-for-go/profiles/preview/resources/mgmt/resources"
    "github.com/azure/azure-sdk-for-go/services/compute/mgmt/2021-03-01/compute"
    "github.com/azure/azure-sdk-for-go/services/subscription/mgmt/2020-09-01/subscription"
    "github.com/azure/go-autorest/autorest/azure/auth"
    "github.com/ktr0731/go-fuzzyfinder"
)

var selectedsub subscription.model
var selectedrg resources.group
var selectedvm compute.virtualmachine

func main() {
    selectedsub = getsubscription()
    selectedrg = getresourcegroup()
    selectedvm = getvm()

    fmt.printf("sub: %s\nrg: %s\nvm: %s\n", *selectedsub.displayname, *selectedrg.name, *selectedvm.name)

    // this work
    networkinterfacereference := *selectedvm.networkprofile.networkinterfaces
    fmt.printf("%s", *networkinterfacereference[0].id)

    // this doesn't work
    fmt.printf("%s", *selectedvm.networkprofile.networkinterfaces[0].id)
}

...
...
...

func getvm() compute.virtualmachine {
    vmclient := compute.newvirtualmachinesclient(*selectedsub.subscriptionid)
    authorizer, err := auth.newauthorizerfromcli()
    if err == nil {
        vmclient.authorizer = authorizer
    }
    vmlist, err := vmclient.list(context.todo(), *selectedrg.name)
    if err != nil {
        panic(err)
    }

    idx, err := fuzzyfinder.find(vmlist.values(), func(i int) string {
        return *vmlist.values()[i].name
    })
    if err != nil {
        panic(err)
    }

    return vmlist.values()[idx]
}

将鼠标悬停到错误处会显示以下错误消息:

field NetworkProfile *[]compute.NetworkProfile
(compute.VirtualMachineProperties).NetworkProfile on pkg.go.dev

NetworkProfile - Specifies the network interfaces of the virtual machine.

invalid operation: cannot index selectedVM.NetworkProfile.NetworkInterfaces (variable of type *[]compute.NetworkInterfaceReference)compiler (NonIndexableOperand)

正确答案


如果您想要第二种工作方式:

// works
networkinterfacereference := *selectedvm.networkprofile.networkinterfaces
fmt.printf("%s", *networkinterfacereference[0].id)

// this doesn't work
fmt.printf("%s", *selectedvm.networkprofile.networkinterfaces[0].id)

正在研究您遇到的编译错误(p.s.请不要发布 screen-shots of code/errors) - 该错误失败,因为您正在尝试索引 go 中不允许的指针。您只能索引映射、数组或切片。

修复很简单,因为您在工作版本中执行了两 (2) 次指针取消引用,所以您需要在单个表达式中执行两 (2) 相同的操作 - 而且您还需要确保词法绑定顺序,以便索引是指针取消引用后完成:

fmt.Printf("%s", *(*selectedVM.NetworkProfile.NetworkInterfaces)[0].ID)

最后,go 中没有引用传递。一切都是按价值来的。如果您想更改一个值,请向它传递一个指针 - 但该指针仍然只是一个被复制的值。

今天关于《未使用额外变量,无法对数组进行索引》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>