0

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"`
}
bgeveritt
  • 303
  • 5
  • 18
  • 1
    what are you expecting `string { target }` to do? If you are just trying to make a `string` value you can just cast it to a string if its not already one: `string(target)` – joshmeranda Jun 03 '22 at 20:03
  • `target` contains the string value I've passed into the function. I've changed it to the following, but I get the same error: ...`Name: { string(target), }`... – bgeveritt Jun 03 '22 at 20:06
  • 2
    If `target` is already a string you need no '{ ... }', try again with `Name: target` – joshmeranda Jun 03 '22 at 20:08

1 Answers1

1

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)
}
code0x00
  • 543
  • 3
  • 18
  • check this post: https://stackoverflow.com/questions/61440004/understanding-go-composite-literal to further want to know. – code0x00 Jun 03 '22 at 20:16