如何在结构体中重写类型?

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

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中的任何数据进行修改。

根据评论中提到的情况,为自定义类型编写marshalunmarshal函数也是一个不错的选择,而且可能更简单。

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,
  }
}

huangapple
  • 本文由 发表于 2021年11月8日 06:32:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/69877052.html
匿名

发表评论

匿名网友

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

确定