[Go] 利用类型断言把interface{}的转换回原类型

Posted taoshihan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Go] 利用类型断言把interface{}的转换回原类型相关的知识,希望对你有一定的参考价值。

当传参数的时候 ,为了方便 ,参数的类型定义成了interface{} , 如果要给这个原类型的属性赋值 , 就需要强转回去 

例如下面的代码:

func RenderList(w http.ResponseWriter, render interface{}) {
    header := tools.FileGetContent("html/header.html")
    html := tools.FileGetContent("html/list.html")
    t, _ := template.New("list").Parse(html)
    render.(*tools.IndexData).Header=template.HTML(header)
    t.Execute(w, render)
}

注意这里是* , 因为结构体属性赋值要是指针  render.(*tools.IndexData).Header  , 

以上是关于[Go] 利用类型断言把interface{}的转换回原类型的主要内容,如果未能解决你的问题,请参考以下文章

go语言接口断言

Go 类型断言

interface变量存储类型

Golang关于Go中的类型转换

为什么 Go 不支持 []T 转换为 []interface

类型断言的最佳实践