[Go] "Method Declaration" on a custom type

package data

// new type
type distance float64
type distanceKm float64
// add ToKm method to distance type
func (miles distance) ToKm() distanceKm {
	// can work as covertor method
	return distanceKm(miles * 1.60934)
}
func (km distanceKm) ToMiles() distance {
	return distance(km / 1.60934)
}
func Test() {
	d := distance(4.5)
	dkm := d.ToKm()
	print(dkm)
}
  1. Type Definitions: You define new types, distance and distanceKm, which are based on the float64 type. This is a way of creating aliases or new types derived from existing ones, giving them specific contextual meanings. In your case, distance represents miles and distanceKm represents kilometers.

  2. Methods on Types: You then define methods (ToKm and ToMiles) on these types. In Go, a method is a function with a special receiver argument. The receiver appears in its own argument list between the func keyword and the method name. In your methods, miles is the receiver of type distance for the ToKm method, and km is the receiver of type distanceKm for the ToMiles method.

  3. Method Receivers: The receiver can be thought of as the equivalent of this or self in other object-oriented languages, but in Go, it's just a regular parameter and can be named anything. It determines on which type the method can be called.

  4. Method Conversion Logic: Your methods perform a conversion from one unit to another. ToKm converts miles to kilometers, and ToMiles converts kilometers to miles.

This approach is part of Go's way to support object-oriented programming features like methods associated with user-defined types, while still keeping the language simple and ensuring that types and methods remain distinct concepts.

posted @   Zhentiw  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-11-21 [React Typescript] Discriminated unions in components props
2022-11-21 [Typescript] 112. Hard - DeepPick
2022-11-21 [Typescript] getProp<T, P extends PathKeys<T>>(obj: T, path: P): PropType<T, P>
2021-11-21 [QROQ] Query Language
2019-11-21 [HTML5] Using HTMLPortalElement to improve MPA preformance
2019-11-21 [CSS] prefers-reduced-motion
2018-11-21 [Testing] Config jest to test Javascript Application -- Part 2
点击右上角即可分享
微信分享提示