Go 標(biāo)準(zhǔn)包 strings 學(xué)習(xí)(1) Clone,Compare,Contains
事先聲明:理解部分都是自己的理解,可能有錯誤,僅供參考
學(xué)習(xí)go語言 1.20.3版本 標(biāo)準(zhǔn)包里面的函數(shù)
go語言標(biāo)準(zhǔn)包官網(wǎng)
https://pkg.go.dev/std
學(xué)習(xí)strings包的內(nèi)容
官網(wǎng)
https://pkg.go.dev/strings@go1.20.3

func Clone
Clone returns a fresh copy of s. It guarantees to make a copy of s into a new allocation, which can be important when retaining only a small substring of a much larger string. Using Clone can help such programs use less memory. Of course, since using Clone makes a copy, overuse of Clone can make programs use more memory. Clone should typically be used only rarely, and only when profiling indicates that it is needed. For strings of length zero the string "" will be returned and no allocation is made.
翻譯
Clone返回s的新副本。它保證將s的副本生成到新的分配中,這在只保留一個大得多的字符串的一小個子字符串時非常重要。使用克隆可以幫助這類程序使用更少的內(nèi)存。當(dāng)然,由于使用Clone會生成副本,因此過度使用Clone會使程序使用更多內(nèi)存。克隆通常應(yīng)該很少使用,并且僅在分析表明需要它時才使用。對于長度為0的字符串,將返回字符串"",并且不進(jìn)行分配
理解
返回字符串的復(fù)制,可用于從一個很大的字符串截取出來一個小字符串,少用

func?Compare
Compare returns an integer comparing two strings lexicographically. The result will be 0 if a == b, -1 if a < b, and +1 if a > b.
Compare is included only for symmetry with package bytes. It is usually clearer and always faster to use the built-in string comparison operators ==, <, >, and so on.
翻譯
Compare返回一個按字典順序比較兩個字符串的整數(shù)。如果a == b,結(jié)果為0,如果a < b,結(jié)果為-1,如果a > b,結(jié)果為+1。
Compare僅用于與包字節(jié)對稱。使用內(nèi)置的字符串比較運算符==、<、>等通常更清晰,而且總是更快。
例子
理解
返回2個字符串比較大小,經(jīng)過在官網(wǎng)上實驗,會根據(jù)傳入的2個字符串進(jìn)行一個字符一個字符的比較,當(dāng)對應(yīng)位置的字符大小不一樣的時候就直接返回結(jié)果,不管后面了
舉例:
返回 -1
因為 第二個位置的 a 小于 b ,就算后面還有字符,也直接返回 -1
返回 1
因為 cb?的第3個位置沒有值,cbc 有值,所以cbc > cb

func?Contains
Contains reports whether substr is within s.
翻譯
包含報告substr是否在s內(nèi)。
理解
s 是否包含 substr ,包含返回true,不包含返回false
案例
true
false
true
true