2 回答

TA貢獻1842條經驗 獲得超13個贊
創建一個丟棄錯誤結果的包裝函數:
func atoi(s string) int {
value, _ := strconv.Atoi(s)
return value
}
if 45 + atoi(value) >= 90 {
//do something
}
或者,在 之前作為語句進行轉換if并忽略錯誤結果:
if i, _ := strconv.Atoi(value); 45 + i >= 90 {
// do something
}

TA貢獻1804條經驗 獲得超8個贊
我只是想將字符串轉換為整數。
如果我 100% 字符串將是一個數字怎么辦?
我想在 if 語句中將一串數字轉換為 int,如下所示:
if 45 + strconv.Atoi(value) >= 90 {
//do something
}
如果你錯了怎么辦?
為 編寫一個簡單的 Go 包裝函數strconv.Atoi。在 Go 中,不要忽視錯誤。
// ASCII digits to integer.
func dtoi(s string) int {
i, err := strconv.Atoi(s)
if err != nil {
panic(err)
}
return i
}
例如,
package main
import (
"fmt"
"strconv"
)
// ASCII digits to integer.
func dtoi(s string) int {
i, err := strconv.Atoi(s)
if err != nil {
panic(err)
}
return i
}
func main() {
value := "1024"
if 45+dtoi(value) >= 90 {
fmt.Println("do something")
}
}
游樂場:https://play.golang.org/p/I3plKW2TGSZ
輸出:
do something
- 2 回答
- 0 關注
- 125 瀏覽
添加回答
舉報