分类 从c到golang 下的文章

从 C 到 golang

方法与指针

Go中没有类的概念,用结构体承担相应的工作

为任意类型声明方法 func (t Type) Abs() float64

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())
}

输出
1.4142135623730951

- 阅读剩余部分 -