[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)
}
-
Type Definitions: You define new types,
distance
anddistanceKm
, which are based on thefloat64
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 anddistanceKm
represents kilometers. -
Methods on Types: You then define methods (
ToKm
andToMiles
) on these types. In Go, a method is a function with a special receiver argument. The receiver appears in its own argument list between thefunc
keyword and the method name. In your methods,miles
is the receiver of typedistance
for theToKm
method, andkm
is the receiver of typedistanceKm
for theToMiles
method. -
Method Receivers: The receiver can be thought of as the equivalent of
this
orself
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. -
Method Conversion Logic: Your methods perform a conversion from one unit to another.
ToKm
converts miles to kilometers, andToMiles
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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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