package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
books := []string{
"wadidaw",
"bededaw",
"celepaw",
}
str := "books[1]"
index, sliceName, err := getIndex(str)
if err != nil {
panic(err)
}
// Check the index is valid as it will be greater than 0 and less than (slice length - 1)
if index < 0 || index > len(books)-1 {
panic("invalid index")
}
fmt.Println("Slice name : ", sliceName)
fmt.Println("Value : ", books[index])
}
func getIndex(str string) (int, string, error) {
// split the string at [
parts := strings.Split(str, "[")
if len(parts) != 2 {
return 0, "", fmt.Errorf("unable to parse %v, invalid syntax", str)
}
name := parts[0]
index := strings.TrimSuffix(parts[1], "]")
// convert the index into int
indexInt, err := strconv.Atoi(index)
if err != nil {
return 0, "", fmt.Errorf("unable to parse '%s' into int", index)
}
return indexInt, name, nil
}
2条答案
按热度按时间bgtovc5b1#
您需要将字符串解析为代码。
请随意使用围棋场
https://go.dev/play/p/-q2JUn-N4Sg
n9vozmp42#
这里有一个非常简单的方法来解析字符串并获取索引值。