A Tour of Go Methods continued

In fact, you can define a method on any type you define in your package, not just structs.

You cannot define a method on a type from another package, or on a basic type.

package main 

import (
    "fmt"
    "math"
)

type MyFloat float64

func (f MyFloat) Abs() float64 {
    if f < 0 {
        return float64(-f)
    }
    return float64(f)
}

func main() {
    fmt.Println(math.Sqrt2)
    f := MyFloat(-math.Sqrt2)
    fmt.Println(f.Abs())
}

很像OC中的类别

时间: 2024-11-10 13:09:04

A Tour of Go Methods continued的相关文章

A Tour of Go Methods with pointer receivers

Methods can be associated with a named type or a pointer to a named type. We just saw two Abs methods. One on the *Vertex pointer type and the other on the MyFloat value type. There are two reasons to use a pointer receiver. First, to avoid copying t

A Tour of Go Methods

Go does not have classes. However, you can define methods on struct types. The method receiver appears in its own argument list between the func keyword and the method name. package main import ( "fmt" "math" ) type Vertex struct { X,

A Tour of Go For continued

As in C or Java, you can leave the pre and post statements empty. package main import "fmt" func main() { sum := 1 for ; sum < 1000; { sum += sum } fmt.Println(sum) }

A Tour of Go Range continued

You can skip the index or value by assigning to _. If you only want the index, drop the ", value" entirely. package main import "fmt" func main() { pow := make([]int, 10) for i := range pow { pow[i] = i << uint(i) } for _, value

Go Methods and Interfaces

[Go Methods and Interfaces] 1.Go does not have classes. However, you can define methods on struct types. The method receiver appears in its own argument list between the func keyword and the method name. 2.You can declare a method on any type that is

for循环的两种写法

教程 (https://tour.golang.org/methods/21) 里的 for 是这样写的: 其中 for 语句可以改写如下: for n, err := r.Read(b); err != io.EOF; n, err = r.Read(b) { fmt.Printf("n = %v err = %v b = %v\n", n, err, b) fmt.Printf("b[:n] = %q\n", b[:n]) } (当然,golang 里的 for

GO学习笔记 - 函数名前面是否有输入参数肯定是不一样的!!

在刚接触GO语言时候,我相信你也会有这种困惑,为什么有的函数名前面有输入参数,而一些却没有,它们是否有差别?确实有差别,没有输入参数,是一般的函数:有输入参数,是结构的方法,输入参数叫做"方法接收者"!GO语言没有类,方法都定义在结构上了!! 官方教程: 函        数:https://tour.go-zh.org/basics/4 结构体方法:https://tour.go-zh.org/methods/1 实例代码: main.go : 引入了"sunylat/de

golang初学之接口---image

来自golang tour 练习 https://tour.go-zh.org/methods/16 package main import "golang.org/x/tour/pic" import "image" import "image/color" type Image struct{ x, y, width, height int } func (im Image) ColorModel() color.Model { return

Go指南_指针接收者

源地址 https://tour.go-zh.org/methods/4 一.描述 你可以为指针接收者声明方法. 这意味着对于某类型 T,接收者的类型可以用 *T 的文法.(此外,T 不能是像 *int 这样的指针.) 例如,这里为 *Vertex 定义了 Scale 方法. 指针接收者的方法可以修改接收者指向的值(就像 Scale 在这做的).由于方法经常需要修改它的接收者,指针接收者比值接收者更常用. 试着移除第 16 行 Scale 函数声明中的 *,观察此程序的行为如何变化. 若使用值接