Go – building POST body, receive error "invalid composite literal type string"

huangapple go评论121阅读模式
英文:

Go - building POST body, receive error "invalid composite literal type string"

问题

我正在尝试在Go中构建一个POST请求的请求体,但是我一直收到以下错误信息:

无效的复合字面类型字符串

以下是我的代码片段和结构体,我无法弄清楚我做错了什么?

postData := projectPostData{
	Filters: projectFilters{
		Name: string{ // <-- 错误指向了这一行
			target,
		},
	},
}

type projectPostData struct {
    Filters projectFilters `json:"filters,omitempty"`
}

type projectFilters struct {
    Name string `json:"name,omitempty"`
}
英文:

I'm trying to build a POST body in Go, but I keep getting the following error:

invalid composite literal type string

Snippets of my code and structs are below, I'm can't figure out what I'm doing wrong?

postData := projectPostData{
	Filters: projectFilters{
		Name: string{ // <-- Error is referred to on this line 
			target,
		},
	},
}

type projectPostData struct {
    Filters projectFilters `json:"filters,omitempty"`
}

type projectFilters struct {
    Name string `json:"name,omitempty"`
}

答案1

得分: 1

你可以查看下面的代码:

package main 

import(
	"fmt"
)


type projectFilters struct {
	Name string `json:"string,omitempty"`
}

type projectPostData struct {
	Filters projectFilters `json:"filters,omitempty"`
}



func main(){
	target := "test target"

	postData := projectPostData{
		Filters: projectFilters{
			Name: target,
		},
	}
	
	fmt.Println(postData)
}
英文:

You can check the below code:

package main 

import(
	"fmt"
)


type projectFilters struct {
	Name string `json:"string,omitempty"`
}

type projectPostData struct {
	Filters projectFilters `json:"filters,omitempty"`
}



func main(){
	target := "test target"

	postData := projectPostData{
		Filters: projectFilters{
			Name: target,
		},
	}
	
	fmt.Println(postData)
}

huangapple
  • 本文由 发表于 2022年6月4日 03:58:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/72494617.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定