为了账号安全,请及时绑定邮箱和手机立即绑定

填充包含切片的结构

填充包含切片的结构

Go
呼啦一阵风 2023-03-21 16:00:32
我正在尝试收集 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 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}当我尝试通过 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你能帮我理解真正的问题是什么吗?我正在观看视频教程。
查看完整描述

2 回答

?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

我猜这不是你想要的......


您的结构声明略有偏离,例如,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 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

}


查看完整回答
反对 回复 2023-03-21
?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

您将某些字段类型声明为pointers-to-slices,但您向它们提供了slice-of-pointers类型的值。

例如,给定字段Comments *[]Comment,您可以像这样初始化它的值:

Comments: &[]Comment{},

请参阅此处了解更多替代方案:https://play.golang.org/p/l9HQEGxE5MP


同样在切片、数组和映射中,如果元素类型已知,即它不是接口,则可以在元素的初始化中省略类型,只使用花括号,因此代码如下:

[]*Post{&Post{ ... }, &Post{ ... }}

可以更改为:

[]*Post{{ ... }, { ... }}


查看完整回答
反对 回复 2023-03-21
  • 2 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信