使用指针索引 - 指针如何与切片一起工作?

ove*_*nge 0 pointers go slice

在下面的main()代码中:

package main

import (
    "fmt"

    "github.com/myhub/cs61a/poetry"
)

func main() {

    p := poetry.NewPoem([][]string{
        {
            "And from my pillow, looking forth by light",
            "Of moon or favoring stars, I could behold",
            "The antechapel where the statue stood",
            "Of Newton, with his prism and silent face,",
            "The marble index of a mind forever",
            "Voyaging through strange seas of thought, alone.",
        },
        {
            "inducted into Greek and Christian",
            "modes of thinking, must take a longer way around.",
            "Like children born into love, they exult in the here",
            "who have felt separation and grave misgivings, they",
            "and of humanity, and of God. Great literature, like",
            "struggles to reconcile suffering with faith in the ",
        },
    })

    fmt.Printf("%T\n", p[0])

}
Run Code Online (Sandbox Code Playgroud)

p[0] 通过使用以下函数构造函数指向第一节可以正常工作:

package poetry

type Line string
type Stanza []Line
type Poem []Stanza

func NewPoem(s [][]string) Poem {
    var poem Poem
    for _, stanza := range s {
        var newStanza Stanza
        for _, line := range stanza {
            newStanza = append(newStanza, Line(line))
        }
        poem = append(poem, newStanza)
    }

    return poem
}
Run Code Online (Sandbox Code Playgroud)

如果,NewPoem()返回 type 的值*Poem,如下所示:

package poetry

type Line string
type Stanza []Line
type Poem []Stanza

func NewPoem(s [][]string) *Poem {
    var poem Poem
    for _, stanza := range s {
        var newStanza Stanza
        for _, line := range stanza {
            newStanza = append(newStanza, Line(line))
        }
        poem = append(poem, newStanza)
    }

    return &poem
}
Run Code Online (Sandbox Code Playgroud)

然后,p[0]main()给出以下错误:

     Invalid operation: p[0] (type *poetry.Poem does not support indexing)
Run Code Online (Sandbox Code Playgroud)

为什么指向字符串切片的指针不支持p[0]语法?

icz*_*cza 6

为什么指向字符串切片的指针不支持p[0]语法?

简短回答:因为语言规范不允许。

更长的答案:因为很少使用指向切片的指针,为什么用不会使许多人受益的东西使语言复杂化?如果在极少数情况下您确实需要它,只需取消引用指针并索引切片。

请注意,规范允许对数组指针进行索引或切片,因为在使用数组时,指向数组的指针更频繁、更有用(比指向切片的指针)。在此处阅读更多相关信息:切片作为参数传递的切片指针