Golang是否支持创建基于其他类型的复合类型?
Golang是否支持创建基于其他类型的复合类型? 我想要类似这样的功能:
类型 bye
类型 kilo uint64 = 1024 * 字节
等等……
3 回复
不,你试图将一个类型与一个值相乘,这在 Go 中是不可能的,因为类型不是值。常见的做法是定义常量,例如 const Kbyte = 1024 并使用它们,例如标准库 time 包中的用法:time.Sleep(3 * time.Second),其中:
type Duration int64
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
在Go语言中,可以通过类型定义(type definition)和类型别名(type alias)来创建基于其他类型的复合类型。以下是具体实现方式:
1. 类型定义(创建新类型)
type ByteSize uint64
const (
KB ByteSize = 1024
MB ByteSize = 1024 * KB
GB ByteSize = 1024 * MB
)
2. 类型别名(与原类型相同)
type Byte = uint64
var fileSize Byte = 2048
3. 结构体类型(复合类型)
type Config struct {
MaxSize ByteSize
Timeout time.Duration
}
4. 示例:完整的类型定义和使用
package main
import "fmt"
// 定义新类型
type ByteSize uint64
// 定义常量
const (
_ = iota
KB ByteSize = 1 << (10 * iota)
MB
GB
)
// 为类型定义方法
func (b ByteSize) String() string {
switch {
case b >= GB:
return fmt.Sprintf("%.2f GB", float64(b)/float64(GB))
case b >= MB:
return fmt.Sprintf("%.2f MB", float64(b)/float64(MB))
case b >= KB:
return fmt.Sprintf("%.2f KB", float64(b)/float64(KB))
}
return fmt.Sprintf("%d B", b)
}
func main() {
var fileSize ByteSize = 1500 * KB
fmt.Printf("文件大小: %s\n", fileSize) // 输出: 文件大小: 1.46 MB
// 类型转换
var rawSize uint64 = uint64(fileSize)
fmt.Printf("原始大小: %d bytes\n", rawSize)
}
5. 基于现有类型的运算
type Kilometer float64
type Meter float64
func (k Kilometer) ToMeters() Meter {
return Meter(k * 1000)
}
func main() {
distance := Kilometer(2.5)
meters := distance.ToMeters()
fmt.Printf("%.1f km = %.0f meters\n", distance, meters)
}
Go的类型系统允许创建基于任何现有类型的新类型,包括基本类型、结构体、接口等。新类型会继承底层类型的表示方式,但被视为不同的类型,需要进行显式类型转换。

