Golang学习:为基本类型添加方法

栏目: Go · 发布时间: 7年前

内容简介:根据go源码中的1.iota关键字只能用在const常量中,还可以使用。2.可以利用基本类型(比如int)来定义一个自己的自定义类型,然后添加自己想要的方法。同时该类型具有基本类型的属性和方法。

根据 go 源码中的 time/time.go 文件中的代码片段写了一个main方法,如下:

package main

import (
    "fmt"
    "time"
)

// A Weekday specifies a day of the week (Sunday = 0, ...).
type Weekday int

const (
    Sunday    Weekday = iota
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
)

var days = [...]string{
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
}

// String returns the English name of the day ("Sunday", "Monday", ...).
func (d Weekday) String() string { return days[d] }

func main() {
    fmt.Println(Friday.String())
    fmt.Println(Monday.String())
    fmt.Println(Tuesday.String())

    fmt.Println(time.Friday.String())
}

1.iota关键字只能用在const常量中,还可以使用。

2.可以利用基本类型(比如int)来定义一个自己的自定义类型,然后添加自己想要的方法。同时该类型具有基本类型的属性和方法。


以上所述就是小编给大家介绍的《Golang学习:为基本类型添加方法》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Dream Machine

The Dream Machine

M. Mitchell Waldrop / Penguin Books / 2002-8 / USD 16.00

While most people may not be familiar with the name J. C. R. Licklider, he was the guiding spirit behind the greatest revolution of the modern era. At a time when most computers were big, ponderous ma......一起来看看 《The Dream Machine》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具