Go Can';t在不使用另一个变量的情况下索引数组

Go Can';t在不使用另一个变量的情况下索引数组,go,Go,我认为从理论上讲,我错过了参考传递主题,但如果不使用支持networkInterfaceReference 主程序包 进口( “上下文” “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/Az

我认为从理论上讲,我错过了参考传递主题,但如果不使用支持
networkInterfaceReference

主程序包
进口(
“上下文”
“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 selectedsubscription.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)
//这项工作
networkInterfaceReference:=*selectedVM.NetworkProfile.NetworkInterfaces
fmt.Printf(“%s”,*网络接口引用[0].ID)
//这不管用
fmt.Printf(“%s”,*selectedVM.NetworkProfile.NetworkInterfaces[0].ID)
}
...
...
...
func GetVM()compute.VirtualMachine{
vmClient:=compute.newVirtualMachine客户端(*selectedSub.SubscriptionID)
授权人,错误:=auth.NewAuthorizerFromCLI()
如果err==nil{
vmClient.Authorizer=授权人
}
vmList,err:=vmClient.List(context.TODO(),*selectedRG.Name)
如果错误!=零{
恐慌(错误)
}
idx,err:=fuzzyfinder.Find(vmList.Values(),func(i int)字符串{
return*vmList.Values()[i].Name
})
如果错误!=零{
恐慌(错误)
}
返回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)
正在研究您得到的编译错误(请不要发布)-错误失败,因为您正在尝试索引Go中不允许的指针。只能为贴图、数组或切片编制索引

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

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


最后,Go中没有pass-by-reference。一切都有价值。如果要更改某个值,请传递指向该值的指针,但该指针仍然是一个值,只是一个复制的值。

我已将图像更改为转录。谢谢你指出这一点。不幸的是,我已经尝试了你的解决方案。粘贴代码时,我收到了完全相同的错误副本。若要强制词法绑定优先级,请使用括号。我已经相应地更新了答案。