[Go] "Method Declaration" on a custom type

发布时间 2023-11-21 15:54:32作者: Zhentiw
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.