美文网首页
A Tour of GO (4) -- Methods and

A Tour of GO (4) -- Methods and

作者: 陈胖子胖胖胖 | 来源:发表于2016-01-13 11:37 被阅读0次
  1. GO does not have class. However, we can define methods on types.
  • A method is a function with a special receiver argument.
  • The receiver appears in its own argument list between the func keyword and the method name.
    func (v Vertex) Abs() float64 {
    return math.Sqrt(v.Xv.X + v.Yv.Y)
    }
  • Remember: A method is just a function with a receiver argument. This one functions the same as the previous one.
    func Abs(v Vertex) float64 {
    return math.Sqrt(v.Xv.X + v.Yv.Y)
    }
  • Important: You can only declare a method with a receiver whose type is defined in the same package. That includes the built-in type. However you can use
    type MyFloat float64
  • Pointer receivers:
    func (v *Vertex) Scale(f float64) {
    v.X = v.X * f
    v.Y = v.Y * f
    }
    • Method with pointer receivers can modify the value to which the receiver points. ( GO is passing by value by default)

    • Method and pointer indirection. Method will be called automatically even v is a value not a pointer, but function will not.
      var v Vertex
      /* Method /
      v.Scale(5) // OK
      p := &v
      p.Scale(10) // OK
      /
      function */
      ScaleFunc(v) // Compile error!
      ScaleFunc(&v) // OK

    • The equivalent thing happens int the reverse direction. The method takes value as receiver can also takes pointer while function cannot.

    • Using pointer as receiver is encouraged. In general, all methods on a give type should have either value or pointer receivers, but not a mixture of both.

  1. Interfaces
  • An interface type is defined by a set of methods.
    type Abser interface {
    Abs() float64
    }
  • A type implements an interface by implementing the methods.
  • Stringer. A Stringer is a type that can describe itself as a string. The fmt pkg look for this interface to print values.
    type Stringer interface {
    String() string
    }
  1. Error
  • The error type is a built-in interface similar to fmt.Stringer.
    type error interface{
    Error() string
    }
  1. Readers
  • The IO package specifies the io.Readerinterface, which denote the read end of a stream of data.
  1. HTTP servers
    *Package http serves HTTP request using any value that implements http.Handler:
  2. Image
  • Package image defines the Image interface.

相关文章

网友评论

      本文标题:A Tour of GO (4) -- Methods and

      本文链接:https://www.haomeiwen.com/subject/dbhckttx.html