填充包含切片的结构

我正在尝试收集 Go 的基础知识。


我正在尝试在 golang 中呈现一个带有结构预填充值的模板。但没有运气


func ServeIndex(w http.ResponseWriter, r *http.Request) {

    p := &Page{

        Title:   " Go Project CMS",

        Content: "Welcome to our home page",

        Posts: []*Post{

            &Post{

                Title:         "Hello World",

                Content:       "Hello, World Thanks for coming to this site",

                DatePublished: time.Now(),

            },

            &Post{

                Title:         "A Post with comments",

                Content:       "Here is the controversial post",

                DatePublished: time.Now(),

                Comments: []*Comment{

                    &Comment{

                        Author:        "Sathish",

                        Comment:       "Nevermind, I guess",

                        DatePublished: time.Now().Add(-time.Hour / 2),

                    },

                },

            },

        },

    }


    Tmpl.ExecuteTemplate(w, "page", p)

}

这是我的结构定义


import (

    "html/template"

    "time"

)


// Tmpl is exported and can be used by other packages

var Tmpl = template.Must(template.ParseGlob("../templates/*"))


type Page struct {

    Title   string

    Content string

    Posts   *[]Post

}


type Post struct {

    Title         string

    Content       string

    DatePublished time.Time

    Comments      *[]Comment

}


type Comment struct {

    Author        string

    Comment       string

    DatePublished time.Time

}

当我尝试通过 main.go 文件运行此代码时,出现以下错误


../handler.go:60: cannot use []*Comment literal (type []*Comment) as type *[]Comment in field value

../handler.go:62: cannot use []*Post literal (type []*Post) as type *[]Post in field value

你能帮我理解真正的问题是什么吗?我正在观看视频教程。


呼啦一阵风
浏览 124回答 2
2回答

ABOUTYOU

我猜这不是你想要的......您的结构声明略有偏离,例如,a pointer to a slice of Post values您可能想要 Page has ,a slice of Post pointers因为这通常是人们使用切片的方式。您的声明只需要*类型旁边的 put,而不是[]然后您的创建代码将起作用。import (    "html/template"    "time")// Tmpl is exported and can be used by other packagesvar Tmpl = template.Must(template.ParseGlob("../templates/*"))type Page struct {    Title   string    Content string    Posts   []*Post}type Post struct {    Title         string    Content       string    DatePublished time.Time    Comments      []*Comment}type Comment struct {    Author        string    Comment       string    DatePublished time.Time}

慕桂英3389331

您将某些字段类型声明为pointers-to-slices,但您向它们提供了slice-of-pointers类型的值。例如,给定字段Comments *[]Comment,您可以像这样初始化它的值:Comments: &[]Comment{},请参阅此处了解更多替代方案:https://play.golang.org/p/l9HQEGxE5MP同样在切片、数组和映射中,如果元素类型已知,即它不是接口,则可以在元素的初始化中省略类型,只使用花括号,因此代码如下:[]*Post{&Post{ ... }, &Post{ ... }}可以更改为:[]*Post{{ ... }, { ... }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go