亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Go 中使用字符串文字

如何在 Go 中使用字符串文字

Go
繁花不似錦 2023-07-10 14:21:36
在 go 模板中,我想用變量替換下面的字符串:bot := DigitalAssistant{"bobisyouruncle", "teamAwesome", "awesomebotimagename", "0.1.0", 1, 8000, "health", "[email protected]"}假設我想bobisyouruncle用變量替換input我怎樣才能做到這一點?在js中這很簡單:bot := DigitalAssistant{`${input}`, "teamAwesome", "awesomebotimagename", "0.1.0", 1, 8000, "health", "[email protected]"}
查看完整描述

1 回答

?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

在 Go 中,不存在像 es6 那樣的字符串模板文字。但是,您絕對可以使用fmt.Sprintf執行類似的操作。

fmt.Sprintf("hello?%s!?happy?coding.",?input)

在你的情況下,它將是:

bot := DigitalAssistant{

? ? fmt.Sprintf("%s", input),

? ? "teamAwesome",

? ? "awesomebotimagename",

? ? "0.1.0",

? ? 1,

? ? 8000,

? ? "health",

? ? "[email protected]",

}

順便說一句,這是一個好奇的問題。為什么需要在非常簡單的字符串(例如 )上使用字符串模板文字${input}?為什么不只是input?


編輯1

我不能只輸入輸入,因為 go 給出錯誤無法使用輸入(類型 []byte)作為字段值中的類型字符串


[]byte可轉換為字符串。如果您的input類型是[]byte,只需將其寫為string(input).


bot := DigitalAssistant{

? ? string(input),

? ? "teamAwesome",

? ? "awesomebotimagename",

? ? "0.1.0",

? ? 1,

? ? 8000,

? ? "health",

? ? "[email protected]",

}

編輯2

如果值是 int,為什么我不能做同樣的事情?因此,對于括號 1 和 8000 中的值,我不能只執行int(numberinput)or int(portinput),否則我會收到錯誤cannot use numberinput (type []byte) as the type int in field value


可以通過使用顯式轉換來實現從string到或從 到 的轉換。然而,這種方法并不適用于所有類型。[]byteT(v)


例如,要轉化[]byte為int更多的努力是需要的。


// convert `[]byte` into `string` using explicit conversion

valueInString := string(bytesData)?


// then use `strconv.Atoi()` to convert `string` into `int`

valueInInteger, _ := strconv.Atoi(valueInString)?


fmt.Println(valueInInteger)


查看完整回答
反對 回復 2023-07-10
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號