今天翻看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
有疑问加站长微信联系(非本文作者)