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.
- quot Declaration Method custom typequot declaration method custom quot custom-logo volumemount container quot上下number type quot content-type content charset declaration emit declaration annotation explicit springbootapplication componentscan declaration activity_main findviewbyid declaration xxx declaration implicit function语言 main function declaration factorial