Primitive Type based User-Defined Type
type liters float64
type gallons float64
func main() {
gasoline := liters(12.5)
diesel := gallons(32.7)
fmt.Println(gasoline, diesel)
// 12.5 32.7
}
You can create your own type based on primitive type.
When converting a type, Go considers only the value itself.
fmt.Println(gallons(liters(3.14)))
// 3.14
So this example is not wrong, because they are all the float64 values.
liters(1.2) + gallons(3.4) // Error: mismatched types
But, the operation between different types is impossible.
Method Definition
Method is similar to function, but you need to declare the receiver parameter in front of the name of a method.
Method can be defined only for the type defined in the current package.
Let's expand on the previous example.
func (l liters) toGallons() gallons {
return gallons(l * 4.54609)
}
func main() {
testLiter := liters(2)
testGallon := testLiter.toGallons()
fmt.Println(testLiter, testGallon)
// 2 9.09218
}
Go uses a receiver parameter instead of "self" or "this" of other languages.
If the receiver parameter is different, you can duplicate the name of the method.
type width int
type height int
func (w width) toString() string {
str := strconv.Itoa(int(w))
return "The width is " + str
}
func (h height) toString() string {
str := strconv.Itoa(int(h))
return "The height is " + str
}
func main() {
theWidth := width(3)
theHeight:= height(4)
fmt.Println(theWidth.toString())
// The width is 3
fmt.Println(theHeight.toString())
// The height is 4
}
Method with Pointer
type number int
func (n *number) double() {
*n *= 2
}
func main() {
testNum := number(2)
testNum.double()
fmt.Println(testNum)
// 4
}
Note that to invoke a pointer receiver method, you must be able to get a pointer from a value.
Method with Additional Parameter
type number int
func (n number) multiply(m int) number {
return n * number(m)
}
func main() {
theNumber := number(2)
fmt.Println(theNumber.multiply(3))
// 6
}
You can use Method with additional parameters.
'Go' 카테고리의 다른 글
[Go] File handling (0) | 2020.12.02 |
---|---|
[Go] Configure VSCode (0) | 2020.11.28 |
[Go] Basic (0) | 2020.10.26 |
[Go] Variable (0) | 2020.10.21 |
[Go] Data Types (0) | 2020.10.21 |
댓글