【发布时间】:2020-12-22 09:23:58
【问题描述】:
假设我有一个字符串 s。
s := "helloworld"
现在,我的问题是,如果 s 有 'n' 个字节,如果我将 s 传递给函数与将 &s 传递给函数然后访问第 i 个字节,则相对于 'n' 的时间复杂度是多少字符串。
如果我将 &s 传递给函数并访问字符串的第 i 个字节需要 O(1) 时间,那么当我将 s 传递给函数然后访问字符串的第 i 个字节时是否需要 O(n) 时间字符串(因为整个字符串都会被复制)?
我试过了,发现复制一个字符串确实会改变指向它的指针。希望能更清楚地说明这一点。
func main() {
str := "helloworld"
fmt.Println("string pointer 1:", &str)
printStringPointer(str)
}
func printStringPointer(s string) {
fmt.Println("string pointer 2:", &s)
}
输出:
string pointer 1: 0xc000010200
string pointer 2: 0xc000010210
【问题讨论】:
-
字符串已经是类似指针的值。使用
*string是不必要的,而且性能更差。见Garbage collection and correct usage of pointers in Go。
标签: string go pointers pass-by-value