go-zero icon indicating copy to clipboard operation
go-zero copied to clipboard

Set the default value of a slice to a null pointer

Open 1067088037 opened this issue 1 year ago • 3 comments

User {
    Links []string `json:"links,default="`
}

This is a API file. How to set the default value of this slice to a null pointer? I tried setting it to nil but it didn't work.

1067088037 avatar Dec 12 '23 09:12 1067088037

If you want to set the field value to null when there are no links in the JSON payload.

Please try to use a pointer as shown below:

User {
    Links *[]string `json:"links,optional"`
}

reference: https://go-zero.dev/en/docs/tutorials/api/parameter

POABOB avatar Dec 18 '23 08:12 POABOB

I tried it but got an error. Error: user.api line 84:22 mismatched input '[' expecting ID

It's valid to write it this way.

User {
    Links []string `json:"links,optional"`
}

1067088037 avatar Dec 18 '23 12:12 1067088037

Sorry, it seems that api file doesn't support pointer type of slice data. Why you want a null pointer value not a empty slice?

POABOB avatar Dec 18 '23 16:12 POABOB