[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,
distanceanddistanceKm, which are based on thefloat64type. This is a way of creating aliases or new types derived from existing ones, giving them specific contextual meanings. In your case,distancerepresents miles anddistanceKmrepresents kilometers. -
Methods on Types: You then define methods (
ToKmandToMiles) on these types. In Go, a method is a function with a special receiver argument. The receiver appears in its own argument list between thefunckeyword and the method name. In your methods,milesis the receiver of typedistancefor theToKmmethod, andkmis the receiver of typedistanceKmfor theToMilesmethod. -
Method Receivers: The receiver can be thought of as the equivalent of
thisorselfin 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.
ToKmconverts miles to kilometers, andToMilesconverts 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.

浙公网安备 33010602011771号