zoukankan      html  css  js  c++  java
  • golang之method

    method

    Go does not have classes. However, you can define methods on types.

    package main
    
    import (
        "fmt"
        "math"
    )
    
    type Vertex struct {
        X, Y float64
    }
    
    func (v Vertex) Abs() float64 {
        return math.Sqrt(v.X*v.X + v.Y*v.Y)
    }
    
    func (v *Vertex) Scale(f float64) {
        v.X = v.X * f
        v.Y = v.Y * f
    }
    
    func (v Vertex) ScaleValue(f float64) {
        v.X = v.X * f
        v.Y = v.Y * f
    }
    
    func main() {
        v := Vertex{3, 4}
        fmt.Println(v.Abs())
        v.Scale(2)
        fmt.Println(v.Abs())
        v.ScaleValue(2)
        fmt.Println(v.Abs())
    
        p := &v
        p.Scale(2)
        fmt.Println(p.Abs())
    }

    输出如下:

    5
    10
    10
    20

    三个注意点:

    1. Methods with pointer receivers can modify the value to which the receiver points 。

    2. methods with pointer receivers take either a value or a pointer as the receiver when they are called:

    var v Vertex
    v.Scale(5)  // OK
    p := &v
    p.Scale(10) // OK

    3. methods with value receivers take either a value or a pointer as the receiver when they are called:

    var v Vertex
    fmt.Println(v.Abs()) // OK
    p := &v
    fmt.Println(p.Abs()) // OK

    interface

    package main
    
    import (
        "fmt"
    )
    
    type I interface {
        M()
    }
    
    type T struct {
        S string
    }
    
    func (t *T) M() {
        fmt.Println(t.S)
    }
    
    func main() {
        var i I
        t := T{"hello"}
        i = &t
        i.M()
    
        v := T{"world"}
        i = v
        i.M()
    }

    main函数后半段代码会报错:cannot use v (type T) as type I in assignment: T does not implement I (M method has pointer receiver)

    如果把M的receiver类型改成value:

    func (t T) M() {
        fmt.Println(t.S)
    }
    

    main函数的代码将正常运行。

  • 相关阅读:
    魅族note手机 图片打马赛克
    魅蓝note手机一键root
    eclipse启动时return code 13
    Eclipse adt 23中运行百度地图官网上的demo出现fatal错误
    windows上部署svn服务器
    windows下jenkins slave 搭建
    图片懒加载
    tomcat7 设置静态资源的expires过期时间
    如何将不带www的根域名301重定向到带www的主域名
    简单的防止图片另存为
  • 原文地址:https://www.cnblogs.com/gattaca/p/7890726.html
Copyright © 2011-2022 走看看