copy函数可以直接使用string作为源

dingkaich · · 538 次点击 · 开始浏览    置顶
这是一个创建于 的主题,其中的信息可能已经有所发展或是发生改变。

今天翻看net/http/lookup.go包的时候,惊奇的发现以下代码段: func lookupProtocolMap(name string) (int, error) { var lowerProtocol [maxProtoLength]byte n := copy(lowerProtocol[:], name) lowerASCIIBytes(lowerProtocol[:n]) proto, found := protocols[string(lowerProtocol[:n])] if !found || n != len(name) { return 0, &AddrError{Err: "unknown IP protocol specified", Addr: name} } return proto, nil } 注意这里直接将入参的name 放到了copy函数的src函数位置,以前没见过。这里直接翻看发现: builint.go里记录了copy函数的详细用法: // The copy built-in function copies elements from a source slice into a // destination slice. (As a special case, it also will copy bytes from a // string to a slice of bytes.) The source and destination may overlap. Copy // returns the number of elements copied, which will be the minimum of // len(src) and len(dst). func copy(dst, src []Type) int 作为特殊的用途,这里的源端可以直接是string.忽然觉得挺好,避免的了我们自己直接copy

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

538 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传