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 < {
return float64(-f)
}
return float64(f)
} func main() {
fmt.Println(math.Sqrt2)
f := MyFloat(-math.Sqrt2)
fmt.Println(f.Abs())
}

很像OC中的类别

A Tour of Go Methods continued的更多相关文章

  1. 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 method ...

  2. A Tour of Go Methods

    Go does not have classes. However, you can define methods on struct types. The method receiver appea ...

  3. A Tour of Go Methods and Interfaces

    The next group of slides covers methods and interfaces, the constructs that define objects and their ...

  4. A Tour of Go Range continued

    You can skip the index or value by assigning to _. If you only want the index, drop the ", valu ...

  5. A Tour of Go For continued

    As in C or Java, you can leave the pre and post statements empty. package main import "fmt" ...

  6. Go Methods and Interfaces

    [Go Methods and Interfaces] 1.Go does not have classes. However, you can define methods on struct ty ...

  7. Go指南练习_图像

    https://tour.go-zh.org/methods/25 一.题目描述 还记得之前编写的图片生成器吗?我们再来编写另外一个,不过这次它将会返回一个 image.Image 的实现而非一个数据 ...

  8. Go指南练习_rot13Reader

    https://tour.go-zh.org/methods/23 一.题目描述 有种常见的模式是一个 io.Reader 包装另一个 io.Reader,然后通过某种方式修改其数据流. 例如,gzi ...

  9. Go指南练习_Reader

    https://tour.go-zh.org/methods/22 一.题目描述 实现一个 Reader 类型,它产生一个 ASCII 字符 'A' 的无限流. 二.题目分析 io 包指定了 io.R ...

随机推荐

  1. http://jingyan.baidu.com/article/e4511cf33479812b855eaf67.html

    http://jingyan.baidu.com/article/e4511cf33479812b855eaf67.html

  2. Android:实现退出确认对话框

    在Android平台上捕获Back键的事件,super.onBackPressed()是执行系统的默认动作,就是退出当前activity,我们要做的就是重写onBackPressed()函数, pub ...

  3. 配置SQL Server 2008服务器

    怎么配置SQL Server 2008服务器_百度经验 http://jingyan.baidu.com/article/9faa7231a922c1473c28cb23.html 1.验证安装是否成 ...

  4. Oracle 学习笔记 常用查询命令篇

    1.查询某个用户下有多少张表 有时候很有用  select count(*) from dba_tables t where t.owner='SCOTT';

  5. [置顶] Maven多模块项目 eclipse热部署 Maven项目实现 tomcat热部署 二

    最近看到有好多童鞋比较热衷热部署,特别是多模块的项目,其实这热部署如果多模块比较大资源,容易内存溢出或者电脑卡住,并不建议这么做. 不过了解下也没有关系,这里我就在说说热部署的另外一种方法,因为我之前 ...

  6. 微信公众平台 Premature end of file

    今天在研究微信公众平台 自动接收发送消息的时候,在如下代码: public String processRequest(HttpServletRequest request) { String res ...

  7. word文档左侧显示目录

    word2007  选择word的视图,然后选择文档结构图

  8. Linux 根文件系统制作

    1.创建根文件目录 mkdir rootfs(名字是随便取的) 2.创建子目录 cd rootfs mkdir bin dev etc lib proc sbin sys usr mnt tmp va ...

  9. 数组中所有重复次数大于等于minTimes的数字

    class Program { static void Main(string[] args) { int[] input = { 1, 1, 1, 2, 2, 5, 2, 4, 9, 9, 20 } ...

  10. 一滴一点vim(学习+备忘)

    普通模式: h j k l 分别是左下上右方式移动: :w 保存修改 :q 推出 :wq 保存修改并退出 :q! 放弃修改强制推出 x 删除光标所在位置字符 i 在光标所以位置插入字符 删除类命令: ...