了解切片索引语义

这个问题的答案可能是“好吧,这就是Go的方式”,但我想了解以下行为背后的原因,即索引值类型的切片:


package main


import (

    "fmt"

)


type S struct {

    Data string

}


func main() {

    s := []S{

        {"first"},

        {"second"},

        {"third"},

    }

    

    // # 1

    // This does not modify "s"

    first := s[0]

    first.Data = "something else"

    fmt.Println(s)

    

    // # 2

    // ...but this does?

    s[0].Data = "woah"

    fmt.Println(s)

    

    // # 3

    // ...and this makes sense but feels inconsistent with the previous block

    second := &s[1]

    second.Data = "this makes sense"

    fmt.Println(s)

}

我的问题是,为什么更新给定的切片编译但不编译?#2var element S = s[0]var element *S = s[0]


开心每一天1111
浏览 102回答 1
1回答

蓝山帝景

first := s[0]创建 的副本 并赋值给 ,类型为 。s[0]firstSs[0].Data = "woah"是直接分配,非常简单。second := &s[1]将指针指定给 ,类型为 。因此修改,因为它是一个指针。请注意,Go 将点同时用于成员访问和指针访问(在 C 中,这将是运算符)。s[1]second*Ssecond.Datas[1].Data->编写和理解这一点的等效方法是:var first Sfirst = s[0]var second *Ssecond = &s[1]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go