博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Go语言中的方法(Method Sets)
阅读量:7022 次
发布时间:2019-06-28

本文共 1870 字,大约阅读时间需要 6 分钟。

  hot3.png

 

物以类聚,人以群分。事物必以类分,以形命名。开始一个个学习Go语言中有哪些数据类型,以及这些类型的特点。

Go语言中的方法是函数之外一个特别的概念。在Go语言的参考中说:

A type may have a method set associated with it (§Interface types, §Method declarations).

  1. The method set of an interface type is its interface.

  2. The method set of any other type T consists of all methods with receiver type T.

  3. The method set of the corresponding pointer type *T is the set of all methods with receiver *T or T (that is, it also contains the method set of T).

  4. Any other type has an empty method set.

  5. In a method set, each method must have a unique method name.

意即,可以为所有自己定义的数据类型定义和该类型相关的方法。在Go里面没有严格的对象的概念,却有方法的概念。两个特殊的地方是:

1. interface是一个抽象的数据类型,它本身就是一个方法集。
2. 要注意type *T和type T不一样。实践中发现区别只在于指针上,type *T的方法操作原数据,type T的方法操作原数据的一个拷贝。type *T和type T定义的方法能互相用,不能重名。
3. 所有方法必需有单独的名字,并且不能动态重载。要完成动态重载可以用interface。

下面这个例子给自定义的浮点数建立Abs()方法:

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

下面这个例子给结构体和结构体指针定义两个方法:

package main  

 
import (  
      "fmt"  
      "math"  
)  
 
type Vertex1  struct {  
    X, Y float64  
}  
 
func (v Vertex1) Scale(f float64) {  
    v.X  = v.X  * f  
    v.Y  = v.Y  * f  
}  
 
func (v Vertex1) Abs() float64 {  
      return math.Sqrt(v.X  *v.X  + v.Y  *v.Y)  
}  
 
 //不能再定义方法(v *Vertex1) Abs() float64   
 
type Vertex2  struct {  
    X, Y float64  
}  
 
func (v  *Vertex2) Scale(f float64) {  
    v.X  = v.X  * f  
    v.Y  = v.Y  * f  
}  
 
func (v  *Vertex2) Abs() float64 {  
      return math.Sqrt(v.X  *v.X  + v.Y  *v.Y)  
}  
 
func main() {  
    v1  :  = Vertex1{  3,  4}  
    v1.Scale(  5)  
    fmt.Println(v1, v1.Abs())  
 
    pv1  :  =  &Vertex1{  3,  4}  
    pv1.Scale(  5)  
    fmt.Println(pv1, pv1.Abs())  
 
    v2  :  = Vertex2{  3,  4}  
    v2.Scale(  5)  
    fmt.Println(v2, v2.Abs())  
 
    pv2  :  =  &Vertex2{  3,  4}  
    pv2.Scale(  5)  
    fmt.Println(pv2, pv2.Abs())  
}  
 /*
  will out put:
  {3, 4} 5
  &{3, 4} 5
  {15, 20} 25
  &{15, 20} 25
*/

转载于:https://my.oschina.net/iyf/blog/552644

你可能感兴趣的文章
Siebel NextRecord And DeleteRecord In Loops Skips Record
查看>>
SpringMVC源码解读 - HandlerMapping - AbstractUrlHandlerMapping系列request分发
查看>>
hello reactjs
查看>>
springMVC实现拦截器
查看>>
Java bean中布尔类型使用注意
查看>>
实验结果处理的一些问题
查看>>
【Android市场】提交应用的一点经验分享
查看>>
SQL Server中事务处理的注意事项
查看>>
MAC使用小技巧
查看>>
Hibernate配置详细解释(转 )
查看>>
JS操作节点
查看>>
svn 的patch p0和p1有什么区别
查看>>
python&&Java&&jsp+servlet连接数据库报错收藏(sql server,mysql)
查看>>
远程访问(HttpClient和HttpResponse的使用) 原型模式
查看>>
【poj解题】3664
查看>>
linux 加固措施
查看>>
OpenStack简单测试性能监控数据记录
查看>>
AngularJS中的依赖注入
查看>>
HttpWebRequest模拟登陆,存储Cookie以便登录请求后使用
查看>>
八进制
查看>>