主要内容
主要根据自己在开发过程中的使用经验,总结一下常用的基础包的使用方式;
可能会有疏漏和错误,主要是强迫自己来进行总结;
归纳列表
1.string & strconv
strconv – 数字转换
strconv包最常用的是整型,浮点型,布尔等类型和字符串的转换;
FormatBool -- "true"/"false"
FormatFloat
FormatInt
FormatUint
ParseBool
ParseFloat
ParseInt
ParseUint
Itoa -- 转字符串
Atoi -- 转int
## 其中FormatFloat的使用细节,可以简化大部分浮点数的格式化问题
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
f: 需要格式化的浮点数
fmt: 格式化表述,如下
prec: 精度(小数位数)
bitSize: 保存字节大小(64->32可能会进行四舍五入),特别的是,-1让函数自己判断需要使用的位数
fmt格式化:
'b' : -ddddp±ddd, 二进制指数
'e'/'E' : -d.dddde±dd/-d.ddddE±dd,十进制指数
'f' : -ddd.dddd,非指数
'g'/'G' : 对于大数相当于'e'/'E' ,否则和'f'一样
- strconv – 字符串转换*
其实strconv来做字符串转换的时间很少,主要包含quote,ascii相关转换;以及将数字转换和字符串转换相结合的AppendXXX函数;
func Quote(s string) string
func QuoteRune(r rune) string
func QuoteRuneToASCII(r rune) string
func QuoteRuneToGraphic(r rune) string
func QuoteToASCII(s string) string
func QuoteToGraphic(s string) string
func Unquote(s string) (string, error)
func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error)
func AppendBool(dst []byte, b bool) []byte
func AppendFloat(dst []byte, f float64, fmt byte, prec, bitSize int) []byte
func AppendInt(dst []byte, i int64, base int) []byte
func AppendQuote(dst []byte, s string) []byte
func AppendQuoteRune(dst []byte, r rune) []byte
func AppendQuoteRuneToASCII(dst []byte, r rune) []byte
func AppendQuoteRuneToGraphic(dst []byte, r rune) []byte
func AppendQuoteToASCII(dst []byte, s string) []byte
func AppendQuoteToGraphic(dst []byte, s string) []byte
func AppendUint(dst []byte, i uint64, base int) []byte
strings – UTF-8字符串操作
Package strings implements simple functions to manipulate UTF-8 encoded strings.
包括以下常见操作:包含(contain),查找(indexOf),替换(replace),分割(split),大小写(to),修剪(trim)
初次之外还封装了三个工具对象:Builder,Reader,Replacer
1. replace操作不支持正则;
2. 善用Builder,对比+运算符;
3. Replacer可同时替换多个old-new对,可以和io操作前(WriteString);
4. trim可以自定义规则函数;
2. regexp(正则)
首先golang实现的正则语法规则和Perl, Python以及大多数其他语言一致;同时支持扩展ERE; 同时支持POSIX模式(https://swtch.com/~rsc/regexp/regexp2.html#posix)–最长匹配原则;支持基于正则规则的查找,匹配,替换,分割等操作;
## 创建一个正则表达式规则对象(Regexp)
func Compile(expr string) (*Regexp, error)
func CompilePOSIX(expr string) (*Regexp, error)
普通模式表达式可通过调用Longest()函数转换为POSIX模式;
## 语法错误,直接panic
func MustCompile(str string) *Regexp
func MustCompilePOSIX(str string) *Regexp
## 查找
FindXxx() string
## 匹配
MatchXxx() bool
## 替换
ReplaceXxx() string
## 分割
func (re *Regexp) Split(s string, n int) []string
n:分割后数组最大长度
同时还有"regexp/syntax"
包,实现对正则语法规则的解析,能得到(a(?:(?:)|b)|d)
类似的语法表达式,这个包没有研究过,也没使用过…
3.time & timer
可以参考另一篇博文:https://mp.youkuaiyun.com/mdeditor/90440503#
4.bytes
bytes包含实现了字节数组相关操作,在呈现上和strings类似,但是更重要的它封装了Buffer,Reader对象,在开发过程中经常用来当缓存使用;
## 等于
EqualXXX
## 包含
ContainXXX/HasXXX
## 查找
IndexXXX
## 替换
ReplaceXXX
## 分割
SplitXXX
## 修剪
TrimXXX
## Buffer
同时实现了io.Writer/io.Reader接口
有最大大小限制,超过会panic(ErrTooLarge)
理解cap,len的含义
## Reader
实现了io.Reader接口
常用做把原始[]byte数据封装为Reader传递给下游,并不需要手动Close
Buffer和Reader支持读写的原始数据类型包括[]byte,string,rune等
5.fmt
字符串格式化和标准输出,并支持以默认空格为分割符(格式化输入)从标准输入获取数据并解析到对应变量;
6. io
主要包含io相关的基础操作,接口定义以及一些基础实现;
基础操作主要包括:复制,读,写,通道;已经针对特殊场景的wrap函数
接口定义:Writer,Reader,Closer, Seeker, ReadCloser/WriteCloser, ReadSeeker/WriteSeeker, ReadWriter
基础实现:ByteReader/ByteWriter, PipeReader/PipeWriter
## 主要了解一下Pipe
核心就是这行代码,使用的是[]byte类型的channel,实现了pipe的效果;
wrCh chan []byte
func Test_pipe(t *testing.T) {
r, w := io.Pipe()
go func() {
for i := 0; i < 10; i++ {
w.Write([]byte(fmt.Sprintf("%d", i)))
time.Sleep(time.Microsecond * 500)
}
w.Close()
}()
go func() {
for {
buf := make([]byte, 10)
n, err := r.Read(buf)
println(n, err, string(buf))
println("\n")
if err != nil {
println(err.Error())
break
}
}
}()
select {}
}
还有一个很好用的包装:
LimitedReader
7.bufio
都是基础的IO操作,封装了Reader,Writer,Scanner三个对象,简单的从它的定义就能看出端倪来:
优化少量,频繁读写的场景
// Reader implements buffering for an io.Reader object.
type Reader struct {
buf []byte
rd io.Reader // reader provided by the client
r, w int // buf read and write positions
err error
lastByte int // last byte read for UnreadByte; -1 means invalid
lastRuneSize int // size of last rune read for UnreadRune; -1 means invalid
}
type Writer struct {
err error
buf []byte
n int
wr io.Writer
}
type Scanner struct {
r io.Reader // The reader provided by the client.
split SplitFunc // The function to split the tokens.
maxTokenSize int // Maximum size of a token; modified by tests.
token []byte // Last token returned by split.
buf []byte // Buffer used as argument to split.
start int // First non-processed byte in buf.
end int // End of data in buf.
err error // Sticky error.
empties int // Count of successive empty tokens.
scanCalled bool // Scan has been called; buffer is in use.
done bool // Scan has finished.
}
8.io/ioutil
封装了几个很方便的函数实现
func NopCloser(r io.Reader) io.ReadCloser
func ReadAll(r io.Reader) ([]byte, error)
func ReadDir(dirname string) ([]os.FileInfo, error)
func ReadFile(filename string) ([]byte, error)
func TempDir(dir, prefix string) (name string, err error)
func TempFile(dir, pattern string) (f *os.File, err error)
func WriteFile(filename string, data []byte, perm os.FileMode) error
9 .log
实现了标准的日志,以及一些场景下的特殊方法Fatal,Panic等;
这个包只实现了基础的日志功能,在实际使用中我们会进行包装,比如go-logging
## 设置格式化的标志(时间/文件名/行数)
func SetFlags(flag int)
## 设置日志前缀
func SetPrefix(prefix string)
## 设置调用深度并输出日志(在flag的Lshortfile/Llongfile设置时有效)
func Output(calldepth int, s string) error
## 绑定IO输出
func SetOutput(w io.Writer)
10.fmt
格式化IO,包括Scan,Print以及字符串格式化,记住一些常用的格式化verbs的表示方式:
--
%v the value in a default format
when printing structs, the plus flag (%+v) adds field names
%#v a Go-syntax representation of the value
%T a Go-syntax representation of the type of the value
%% a literal percent sign; consumes no value
%f default width, default precision
%9f width 9, default precision
%.2f default width, precision 2
%9.2f width 9, precision 2
%9.f width 9, precision 0
+ always print a sign for numeric values;
guarantee ASCII-only output for %q (%+q)
- pad with spaces on the right rather than the left (left-justify the field)
# alternate format: add leading 0 for octal (%#o), 0x for hex (%#x);
0X for hex (%#X); suppress 0x for %p (%#p);
for %q, print a raw (backquoted) string if strconv.CanBackquote
returns true;
always print a decimal point for %e, %E, %f, %F, %g and %G;
do not remove trailing zeros for %g and %G;
write e.g. U+0078 'x' if the character is printable for %U (%#U).
' ' (space) leave a space for elided sign in numbers (% d);
put spaces between bytes printing strings or slices in hex (% x, % X)
0 pad with leading zeros rather than spaces;
for numbers, this moves the padding after the sign
参考:fmt
11.sync
同步原语和原子操作