In the below main()
code:
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])
}
p[0]
works fine by pointing to first stanza using below function constructor:
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
}
If, NewPoem()
returns value of type *Poem
, as shown below:
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
}
then, p[0]
in main()
gives below error:
Invalid operation: p[0] (type *poetry.Poem does not support indexing)
Why pointer to slice of slice of strings does not support p[0]
syntax?