gpt4 book ai didi

go - 何时对基本类型使用类型定义

转载 作者:数据小太阳 更新时间:2023-10-29 03:03:25 25 4
gpt4 key购买 nike

我的问题是关于 Go 中的类型定义以及何时将其用于基本类型。
考虑以下示例。
我有这个结构,它代表我的数据库中的一行:

type DBEntityAttribute struct {
Id uint64
EntityId uint64
EndPointNumber uint8
AttributeNumber uint8
ParentId uint64
Value string
Tag int
ContentType sql.NullString
Maturity int
Author int
AttributeType string
IsNegated bool
}

EntityId 和 AttributeNumber 是我在代码各处的许多其他结构中使用的属性。
现在我想将它重构为这样的东西:

type EntityId uint64

type AttributeNumber uint8

type DBEntityAttribute struct {
Id uint64
EntityId EntityId
EndPointNumber uint8
AttributeNumber AttributeNumber
ParentId uint64
Value string
Tag int
ContentType sql.NullString
Maturity int
Author int
AttributeType string
IsNegated bool
}

这将允许我在一个地方更改 EntityId 和 AttributeNumber 的类型。此外,例如,当我将 entityId 作为函数参数传递时,我现在可以为其指定特定的 EntityId 类型,而不是匿名 uint64。

我现在的问题是:

  • 这是好的 Go 代码吗?
  • 我应该在哪里停下来,意思是我应该为代码中其他地方使用的每个属性声明一个不同的类型吗?还是只为重要的人?

我知道这可能是主观的,但 Go 社区通常会就某些模式达成一致,我想遵守他们的指导方针。

最佳答案

关于何时使用自定义类型没有硬性规定。我的个人规则是:

有理由时使用自定义类型。

您想要在单个位置更改基础类型的原因似乎是一个很好的理由。

其他好的理由是:

  • 分配自定义 JSON(非)编码器或其他接口(interface)方法
  • 作为文档
  • 与常量结合,充当枚举
  • 提高了类型安全性(避免将 FooID 意外分配给 BarID)

关于go - 何时对基本类型使用类型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49490742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com