2

Golangのhtml/templateを使った下記のコードがうまく動きません。
template内でrangeを使い、struct a の rの要素を$index2で一つずつ展開させたいのですが、展開されず、Stdoutに何も表示されません。どうすれいいのでしょうか?

このコードのPlayGround


package main

import (
    "html/template"
    "os"
)

type a struct {
    r []string
}

func main() {
    my_struct := a{r:[]string{"A", "B", "C"}}
    template_string := "{{ range $index, $index2 := .r }} {{ $index2 }}{{ end }}"
    //range
    temp := template.Must(template.New("foo").Parse(template_string))
    temp.Execute(os.Stdout, my_struct)

}

1 件の回答 1

2
temp.Execute(os.Stdout, my_struct)

を、

if err := temp.Execute(os.Stdout, my_struct); err != nil {
    fmt.Println(err)
}

として実行しますと、以下のメッセージが表示されます。

template: foo:1:28: executing "foo" at <.r>: r is an unexported field of struct type main.a

つまり、フィールド rR など(大文字で始まる名前)にする必要がありそうです。

実際、R に置き換えて実行しますと、

$ go run a.go
   A B C

となります。

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。