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

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

使用配置中的值更新字符串數組

使用配置中的值更新字符串數組

Go
慕工程0101907 2023-06-26 15:44:11
我有以下函數,需要在兩個選項中提供帶有數據的字符串提供了配置中的值(只能更改7MB或 的值3MB)所有前綴都是相同的如果未提供配置,則回退到默認值,7MB 并且3MB例子如果我沒有從配置 API 中獲取任何值,該函數應該返回默認值,該值是硬編碼在函數中的。像這樣:“l_sh_dit conf_data 7MB  l_sh_dit cert_data 3MB”如果我從應用程序中獲得價值,config假設分別為 1MB(conf)和 100MB(cert),則該函數的輸出應該看起來像 l“l_sh_dit conf_data 1MB  l_sh_dit cert_data 100MB”問題是我已經有了defaults值hard-coded,如何才能element有效地更新數組中的每個值中的最后一個值(數字 10M 或所有其他值)?我嘗試過使用字符串生成器 API,但沒有成功,因為這有點棘手,這里可能缺少什么?func getShCfg() string{var out []stringvar b1 strings.Builderla:= "l_sh_dit conf_data 7MB"lb := "l_sh_dit cert_data 3MB"cfg, ok := c.(config.Configuration)if !ok {    log.Errorf(“error:”, c)    return ""}// here I got the data from config, else fallback to defaults if len(cfg.A) > 0 {   // HERE is my problem which doesn’t works   b1.WriteString("l_sh_dit")   b2 := b1   b2.WriteString("conf_data")    b3 := b2   b3.WriteString(cfg.A)    out = append(out, b3)} else {    out = append(out, la)}// here I got the data from config, else fallback to defaults if len(cfg.B) > 0 {   // HERE is my problem which doesn’t works   b1.WriteString("l_sh_dit")   b2 := b1   b2.WriteString("cert_data")    b3 := b2   b3.WriteString(cfg.B)    out = append(out, b3)} else {    out = append(out, lb)}return strings.Join(out, ";\n\r") + ";"}
查看完整描述

1 回答

?
繁花如伊

TA貢獻2012條經驗 獲得超12個贊

您的程序失敗的原因之一是您正在復制不允許的非零strings.Builder實例。

Builder 用于使用 Write 方法有效地構建字符串。它最大限度地減少了內存復制。零值即可使用。不要復制非零構建器。

另外,我在這里可能是錯的,但我相信構建器的目的是在處理足夠復雜的規則時提供更好的性能,其中使用大量單獨的步驟來構建字符串是合理的。然而,您的情況不是其中之一,因為您所需要的只是一個串聯即可獲得您想要的東西。

type Cfg struct { A, B string }


func getShCfg(c Cfg) string {

? ? var out []string


? ? la := "l_sh_dit conf_data 7MB"

? ? lb := "l_sh_dit cert_data 3MB"


? ? if len(c.A) > 0 {

? ? ? ? out = append(out, "l_sh_dit conf_data " + c.A)

? ? } else {

? ? ? ? out = append(out, la)

? ? }

? ? if len(c.B) > 0 {

? ? ? ? out = append(out, "l_sh_dit cert_data "+c.B)


? ? } else {

? ? ? ? out = append(out, lb)

? ? }


? ? return strings.Join(out, ";\n\r") + ";"


}

https://play.golang.com/p/WKMXxCXGuTt


此外,如果配置屬性的數量增加并且您希望避免編寫太多 if-else,那么您始終可以將該邏輯提取到函數中。


func getCfgProp(key, val, def string) string {

? ? if len(val) > 0 {

? ? ? ? return key + " " + val

? ? }

? ? return key + " " + def

}

https://play.golang.com/p/daXqV4-Umza


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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