11
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go template で、「can't evaluate field X in type Y」のエラー

Last updated at Posted at 2019-07-04

エラー内容

range ループ内で、rangeに与えていない変数を利用しようとすると、
「can't evaluate field X in type Y」というエラーが発生する

エラーが発生する例

変数 exFlag が true の場合に $v を表示する

.go
    {{ range $i, $v := .Values }}
      {{ if .exFlag }}
      {{ $v }}
      {{ end }}
    {{ end }}

なぜか

When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.

rangeの中では、先頭に「.」がつく変数は、「$.」でアクセスできるようになるようです。

正しい例

.go
    {{ range $i, $v := .Values }}
      {{ if $.exFlag }}
      {{ $v }}
      {{ end }}
    {{ end }}

まとめ

常識なのかもしれませんが、
私は、はまったので誰かの役に立てれば。

参考:
https://stackoverflow.com/questions/43263280/go-template-cant-evaluate-field-x-in-type-y-x-not-part-of-y-but-stuck-in-a

11
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?