Hello everyone, my name is Xie Wei, I am a programmer.
In the near future, we will continue to update the learning content of the built-in library. The main references are: GODoc, and source code
Conversions between strings and numeric and Boolean types are frequent in everyday coding. So it’s worth exploring the built-in Strconv library.
The topic of this section is conversion between strings and other primitive data types.
In addition, there are other types of transformations, most notably JSON, which I’ll cover next time.
Outline:
- What are the basic data types
- Common apis summarized by myself
- Common apis given in documentation
- What you learned
What are the basic data types
-
Since this is a conversion between strings and other basic data classes, what are the basic data types that strings can operate on?
-
What are the similarities between functions that convert strings to other data types?
-
How are other data types converted to strings similar?
How do you know these answers?
- Look at the document API
func Atoi(s string) (int, error)
func CanBackquote(s string) bool
func FormatBool(b bool) string
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
func FormatInt(i int64, base int) string
func FormatUint(i uint64, base int) string
func IsGraphic(r rune) bool
func IsPrint(r rune) bool
func Itoa(i int) string
func ParseBool(str string) (bool, error)
func ParseFloat(s string, bitSize int) (float64, error)
func ParseInt(s string, base int, bitSize int) (i int64, err error)
func ParseUint(s string, base int, bitSize int) (uint64, error)
Copy the code
- Basic data types are: Boolean, numeric (integer, floating point)
- Other functions that convert data types to strings use: Format as the keyword
- Functions that convert strings to other data types usually use: Parse as the keyword
What are your common uses
- String to integer: strconv.atoi
func toInt(value string) (result int) {
result, _ = strconv.Atoi(value)
return
}
Copy the code
The principle is: “ABC” — > A *100 + b*10 + C
- Integer to string strconv.Itoa
func toString(value int) (result string) {
result = strconv.Itoa(value)
return
}
Copy the code
- Conversion between a string and a Boolean
func toBool(value string) (result bool) {
result, _ = strconv.ParseBool(value)
return
}
func boolToString(value bool) (result string) {
result = strconv.FormatBool(value)
return
}
Copy the code
- Conversion between a string and a floating point value
func toFloat(value string) (result float64) {
result, _ = strconv.ParseFloat(value, 32)
return
}
func floatToString(value float64) (result string) {
result = strconv.FormatFloat(value, 'E', 1, 32)return
}
Copy the code
Floating-point numbers require attention to precision.
Familiarize yourself with these concepts because values exist in bases:
- -leonard: base 2,8,10,16
- Bitsize: floating point 32,64
As can be seen:
- Parse the string to a different type
- Other types to string, no error handling, keyword: Format
In my opinion, mastering these can handle most scenarios.
API given in documentation
String and integer
func ParseInt(s string, base int, bitSize int) (i int64, err error)
func ParseUint(s string, base int, bitSize int) (n uint64, err error)
func Atoi(s string) (i int, err error)
Copy the code
func toBaseInt(value string) (result int64) {
result, _ = strconv.ParseInt("123"8, 32),return
}
Copy the code
Converts the string of base 8 123 to an integer: 1*8*8+2*8+3*1=83
Therefore, it is possible to convert any base data into an integer. If an error occurs when converting a string to an integer, for example, an error must be reported when the number “128” in base 7 is 8.
There is also unsigned number conversion
func IntToString(value int64) (result string) {
return strconv.FormatInt(value, 8)
}
func mainPrintln(IntToString(123))} >> 173 1*64 + 7*8 + 3 = 64 + 56 + 3 = 123Copy the code
To summarize this transformation:
- Pay attention to the base
- Pay attention to accuracy
Boolean and string
func ParseBool(str string) (value bool, err error)
func FormatBool(b bool) string
Copy the code
Note that:
- Booleans are not just true and false; expressions, such as 0<1, are also false
- String true and false, not in the following case:
FAlse, TRue, tRUE, fALSE
, so either uppercase, lowercase, uppercase, or single character. To avoid this, it is best to use lowercase or uppercase strings
Floating point and string
func ParseFloat(s string, bitSize int) (f float64, err error)
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
Copy the code
You might wonder about the FMT argument, but it’s easy to understand. What does FMT formatting do to floating-point types?
%b Scientific notation for powers of two without fractional parts, with strconv.FormatFloat'b'The conversion format is consistent. For example, -123456p-78 %e scientific notation, for example, -1234.456e+78 Printf("%e", 10.2) + + 1 %E Scientific counting method, for example -1234.456e +78 Printf("%e"F with decimal point but no exponent, e.g. 123.456 Printf("%f", 10.2) 10.200000 %g Select %e or %f as appropriate to produce a more compact (no trailing 0) Printf("%g"Select %E or %f as the case may be to produce a more compact (no trailing 0) Printf("%G"10.20 + 2 I), (10.2 + 2 I)Copy the code
other
func Quote(s string) string func QuoteRune(r rune) string func QuoteRuneToASCII(r rune) string func QuoteRuneToGraphic(r rune) string func QuoteToASCII(s string) string func QuoteToGraphic(s string) stringCopy the code
Simply put, it means to put quotes around things that are suitable for double quotes or within single quotes.
What you learned
- Error handling
It is important to implement a formal error handling mechanism in the project, such as the meaning of the error code, the specific information to display, and so on.
How does that work in general projects?
type ErrorCode struct{
Code int
Message string
}
func (e ErrorCode) Error()string{
return fmt.Sprintf("Code: %d, Message: %s", e.Code, e.Message)
}
var Global strcut {
ErrorRoute = ErrorCode{}
ErrorDB = ErrorCode{}
...
}
Copy the code
This looks similar to strconv library error handling:
- Define a structure
- Implementing the Error interface
type NumError struct {
Func string // the failing function (ParseBool, ParseInt, ParseUint, ParseFloat)
Num string // the input
Err error // the reason the conversion failed (e.g. ErrRange, ErrSyntax, etc.)
}
func (e *NumError) Error() string {
return "strconv." + e.Func + ":" + "parsing " + Quote(e.Num) + ":" + e.Err.Error()
}
Copy the code
- Two implementations of error handling
errors.New()
fmt.Errorf()
Copy the code
reference
- strconv
Iteration in progress
- The first iteration of back end engineer walkthrough is underway
- Iteration in progress
The full text,