Golang – 自定义类型 (Custom Type)

通过自定义类型(Custom Type),可以为特定的业务逻辑或领域概念创建有意义的类型名称。这使得代码更易于理解和维护。

  1. 定义一个新的类型 MessageStatus,基于 string 类型
type MessageStatus string

var Failed = MessageStatus("FAILED")
var Delivered = MessageStatus("DELIVERED")
var finalStatuses = []MessageStatus{Failed, Delivered}

//检查当前MessageStatus是否为最终状态
func (thisStatus MessageStatus) IsFinalStatus() bool {
	for _, status := range finalStatuses {
		if thisStatus == status {
			return true
		}
	}
	return false
}

//把当前MessageStatus转换成String,并且返回
func (thisStatus MessageStatus) String() string {
	return string(thisStatus)
}

2. 范例使用MessageStatus

func main() {
	newStatus := MessageStatus("ACCEPTED")
	fmt.Println(newStatus) // 输出:ACCEPTED
	fmt.Println(newStatus.IsFinalStatus()) //输出:false
	
	//输出:main.MessageStatus , 因为MessageStatus是放在main package当中
	fmt.Println(reflect.TypeOf(newStatus))

	//检查statusString的variable type
	statusString := newStatus.String()
	fmt.Println(reflect.TypeOf(statusString)) //输出:string
}

Loading

Facebook评论