Method definition usage analysis in the Go language

  • 2020-05-26 09:17:50
  • OfStack

This article illustrates method definitions in the Go language as an example. Share with you for your reference. The specific analysis is as follows:

In fact, you can define any method for any type in a package, not just a structure.
You cannot define methods for types or base types from other packages.

package main
import (
    "fmt"
    "math"
)
type MyFloat float64
func (f MyFloat) Abs() float64 {
    if f < 0 {
        return float64(-f)
    }
    return float64(f)
}
func main() {
    f := MyFloat(-math.Sqrt2)
    fmt.Println(f.Abs())
}

I hope this article has been helpful to your programming of Go language.


Related articles: