所以基本上我想知道在 GO 中是否可能,因為我在玩Dereference。例如在下面顯示的代碼中。指針被傳遞給函數,我試圖返回傳遞的指針字符串的一個字母,在給定的示例中是 H,但是slice只能與字符串一起使用。我想知道是否可以使用指針取消引用來做到這一點。代碼示例:func Test(test *string) { if len(*test) > 0 { *test = *test[:1] } strings.ToUpper(*test)}func main() { str := "hello" Test(&str) fmt.Print( str)}
2 回答

達令說
TA貢獻1821條經驗 獲得超6個贊
您需要放在test括號中,即首先取消引用指針,然后對其進行切片。
然后該Test函數仍然不會返回大寫H,因為ToUpper接受并返回一個值。因此,您還需要重新分配 to 的ToUpper輸出*test:
func Test(test *string) {
if len(*test) > 0 {
*test = (*test)[:1] // bracketed `test`
}
*test = strings.ToUpper(*test) // reassign to `test`
}
func main() {
str := "hello"
Test(&str)
fmt.Print(str) // Prints 'H'
}

小唯快跑啊
TA貢獻1863條經驗 獲得超2個贊
是否可以在 Go 中傳遞字符串指針并使其成為字符串切片?
是的:func (ps *string) []string { return []string{*ps} }
- 2 回答
- 0 關注
- 118 瀏覽
添加回答
舉報
0/150
提交
取消