Golang类型转换

I have specific questions for my project

input = "3d6"

I want to convert this string some parts to integer. For instance I want to use input[0] like integer. How can I do this?

For example,

package main

import (
    "fmt"
)

func main() {
    input := "3d6"
    i := int(input[0] - '0')
    fmt.Println(i)
}

Playground: https://play.golang.org/p/061miKcXdIF

Output:

3

There's two problems here:

How to convert a string to an integer

The most straightforward method is the Atoi (ASCII to integer) function in the strconv package., which will take a string of numeric characters and coerce them into an integer for you.

How to extract meaningful components of a known string pattern

In order to use strconv.Atoi, we need the numeric characters of the input by themselves. There's lots of ways to slice and dice a string.

  • You can just grab the first and last characters directly - input[:1] and input[2:] are the ticket.

  • You could split the string into two strings on the character "d". Look at the split method, a member of the strings package.

  • For more complex problems in this space, regular expressions are used. They're a way to define a pattern the computer can look for. For example, the regular expression ^x(\d+)$ will match on any string that starts with the character x and is followed by one or more numeric characters. It will provide direct access to the numeric characters it found by themselves.

    • Go has first class support for regular expressions via its regexp package.