strconv 包含了一系列的转换函数:
字符串转整型
转整型定义了新的错误类型:
type NumError struct {
Func string // the failing function (ParseBool, ParseInt, ParseUint, ParseFloat, ParseComplex)
Num string // the input
Err error // the reason the conversion failed (e.g. ErrRange, ErrSyntax, etc.)
}
func (e *NumError) Error() string {
return "strconv." + e.Func + ": " + "parsing " + Quote(e.Num) + ": " + e.Err.Error()
}
func (e *NumError) Unwrap() error { return e.Err }
var ErrSyntax = errors.New("invalid syntax")
func syntaxError(fn, str string) *NumError {
return &NumError{fn, str, ErrSyntax}
}
var ErrRange = errors.New("value out of range")
func rangeError(fn, str string) *NumError {
return &NumError{fn, str, ErrRange}
}
func baseError(fn, str string, base int) *NumError {
return &NumError{fn, str, errors.New("invalid base " + Itoa(base))}
}
func bitSizeError(fn, str string, bitSize int) *NumError {
return &NumError{fn, str, errors.New("invalid bit size " + Itoa(bitSize))}
}
其他:
const intSize = 32 << (^uint(0) >> 63)
const IntSize = intSize
const maxUint64 = 1<<64 - 1
- ParseUint
func ParseUint(s string, base int, bitSize int) (uint64, error) { const fnParseUint = "ParseUint" if s == "" { return 0, syntaxError(fnParseUint, s) } base0 := base == 0 // 查看是什么进制转换,输入"0b", "0o", "0x" s0 := s switch { case 2 <= base && base <= 36: // valid base; nothing to do case base == 0: // Look for octal, hex prefix. base = 10 if s[0] == '0' { switch { case len(s) >= 3 && lower(s[1]) == 'b': base = 2 s = s[2:] case len(s) >= 3 && lower(s[1]) == 'o': base = 8 s = s[2:] case len(s) >= 3 && lower(s[1]) == 'x': base = 16 s = s[2:] default: base = 8 s = s[1:] } } default: return 0, baseError(fnParseUint, s0, base) } if bitSize == 0 { bitSize = IntSize } else if bitSize < 0 || bitSize > 64 { return 0, bitSizeError(fnParseUint, s0, bitSize) } }
字符串转浮点
字符串转bool
- 字符串和bool
func ParseBool(str string) (bool, error) { switch str { case "1", "t", "T", "true", "TRUE", "True": return true, nil case "0", "f", "F", "false", "FALSE", "False": return false, nil } return false, syntaxError("ParseBool", str) }
- bool 转 字符串
func FormatBool(b bool) string { if b { return "true" } return "false" }
字符串转复数
TODO
网友评论