골란 사용 html/template
(text/template
과 동일한 동작). 인터페이스 유형의 멤버가있는 구조체가있는 경우 기본 유형의 멤버에 액세스 할 수 없습니다 (구체적으로 인터페이스 InnerInterface
을 구현하는 구조체의 필드에 액세스하려고 시도하지만 구조체가 아닌 InnerInterface
인터페이스 유형을 통해 반환됩니다). 유형). 변경템플릿은 기본 유형으로 인터페이스 유형 인 필드를 평가하지 않습니다.
http://play.golang.org/p/ZH8wSK83oM
package main
import "fmt"
import "os"
import "html/template"
type InnerInterface interface{ InnerSomeMethod() }
type MyInnerStruct struct { Title string }
func (mis MyInnerStruct)InnerSomeMethod() { fmt.Println("Just to show we're satisfying the interface") }
type MyOuterStruct struct { Inner InnerInterface }
func main() {
fmt.Println("Starting")
arg := MyOuterStruct{Inner:MyInnerStruct{Title:"test1"}}
err := template.Must(template.New("testtmpl").Parse("{{.Inner.Title}}")).Execute(os.Stdout, arg)
if err != nil { panic(err) }
}
: 완전히 일반적인 인터페이스 type MyOuterStruct struct { Inner InnerInterface }
, 즉 type MyOuterStruct struct { Inner interface{} }
는 제대로 렌더링합니다. 이것은 interface{}
이 렌더링 엔진에 의해 특별히 처리된다고 믿게합니다.
이렇게 필드를 동적으로 평가할 수있을 때마다 interface{}
을 사용하는 것보다 더 좋은 방법이 있습니까?
Tks for this - 내 프로젝트의 구조면에서 Title() 메소드를 인터페이스에 넣지 않아도되지만 요소가 포함됩니다. 템플릿에서 쉽게 액세스 할 필요가있을 때 인터페이스 {} 유형 필드를 사용하여 종료되었습니다. 그것은 완벽하지는 않지만 실행 가능합니다. 그리고 그것은 무슨 일이 일어나고 있는지 분명합니다. –