英文:
How do you rewrite types in struct?
问题
我可以帮你翻译这段代码。以下是翻译好的内容:
无法更改的源代码:
{
"perfectly_normal": "bar",
"fooBool": "0"
}
表格上的内容:
type hwo struct {
normality string `json:"perfectly_normal"`
makeMeBool ?????? `json:"fooBool"`
}
json.Unmarshal(body, hwo)
如何将 "0"/"1" 转换为 false/true 的好方法?
英文:
Source that I can't change:
{
"perfectly_normal": "bar"
"fooBool": "0"
}
What's on the table:
type hwo struct {
normality string `json:"perfectly_normal"`
makeMeBool ?????? `json:"fooBool"`
}
json.Unmarshal(body, hwo)
What's a good way to turn "0"/"1" to false/true?
答案1
得分: 1
你可以使用一个数据传输对象(DTO)和一个方法将传递的DTO转换为所需的struct。
以下是一些伪代码,其中使用DTO根据DTO中的值创建一个新的hwo结构。
这样做的好处是可以在有多个数据需要转换时,对DTO中的任何数据进行修改。
根据评论中提到的情况,为自定义类型编写marshal和unmarshal函数也是一个不错的选择,而且可能更简单。
type hwo struct {
normality string `json:"perfectly_normal"`
makeMeBool boolean `json:"fooBool"`
}
type DTO struct {
normality string
fooBool int
}
func ToHwo(dto DTO) hwo {
fooBool := true
if dto.fooBool == 0 {
fooBool = false
}
return hwo {
normality: dto.normality,
fooBool: fooBool,
}
}
英文:
You could use a DTO and a method to convert the passed DTO in to the desired struct.
Below is some pseudo code where the DTO is used to create a new hwo struct based on the values in the DTO.
This gives the added benefit of being able to mutate any data from the DTO, in the instances where you have more than just a int to boolean conversion.
marshal and unmarshal functions for a custom type as mentioned in the comments are also a good shout and probably simpler.
type hwo struct {
normality string `json:"perfectly_normal"`
makeMeBool boolean `json:"fooBool"`
}
type DTO struct {
normality string
fooBool int
}
func ToHwo(dto DTO) hwo {
fooBool := true
if dto.fooBool == 0 {
fooBool = false
}
return hwo {
normality: dto.nornality,
fooBool: fooBool,
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论