知识点储备
常用类型的对应关系
类型 | golang | 仓颉 |
---|---|---|
整数 | int8 | Int8 |
整数 | int16 | Int16 |
整数 | int32 | Int32 |
整数 | int64 | Int64 |
无符整数 | uint8 | UInt8 |
无符整数 | uint16 | UInt16 |
无符整数 | uint32 | UInt32 |
无符整数 | uint64 | UInt64 |
浮点 | float32 | Float32 |
浮点 | float64 | Float64 |
字符串 | string | String |
字符 | rune | Rune、Char |
布尔值 | bool | Bool |
数组 | []interface{} | Array |
Slice | []interface{} | ArrayList |
Map | map[interface{}]interface{} | HashMap<K, V> |
迁移前的准备
第一步:添加类型别名
type int8 = Int8
type int16 = Int16
type int32 = Int32
type int64 = Int64
type int = Int64
type uint8 = UInt8
type uint16 = UInt16
type uint32 = UInt32
type uint64 = UInt64
type float32 = Float32
type float64 = Float64
type bool = Bool
type rune = Rune
type string = String
第二步:为类型拓展最常用的API
以len()
函数为例
interface Len {
prop size: int
}
extend String <: Len {}
extend Array<T> <: Len {}
extend ArrayList<T> <: Len {}
extend HashMap<K, V> <: Len {}
func len(t: Len): int64 {
return t.size
}
最后:使用别名声明变量
main() {
let i8: int8 = 1
let f64: float64 = 1.0
let bT: bool = true
let map = HashMap<String, Any>()
map["i8"] = i8
map["f64"] = f64
map["bT"] = bT
println("len(map) = ${len(map)}") // 打印map的数据量
// len(map) = 3
let str: string = "你好,仓颉!"
println("len(str) = ${len(str)}") // 打印字符串utf-8数组长度
// len(str) = 18
let chr: Array<rune> = str.toRuneArray()
println("len(chr) = ${len(chr)}") // 打印字符串的字符数组长度
// len(chr) = 6
return 0
}