当前位置:网站首页>Golang type assertion and conversion (and strconv package)
Golang type assertion and conversion (and strconv package)
2022-07-03 20:13:00 【alwaysrun】
List of articles
go It's a strong type of language , It requires explicit type conversion between different types of expressions ; However, there are exceptions :
- When ordinary T Type variable to I Interface type conversion is implicit ;
- When IX Interface variable to I Interface type conversion can be implicit at compile time ;
Type conversion is divided into Type conversion
、 Types of assertions
; The difference is , Type assertions are operations on interface variables .
Type conversion
Only two compatible types can be used Type conversion
:
< Result type variable > := < The target type > ( < expression > )
Conversion conditions
Put variables x Convert to T type (T(x)
), Need to meet :
- x Can be assigned to T type ;
- x The type and T Have the same underlying type (underlying type);
- x The type and T All unnamed pointer types , And the types on which pointers are based are compatible ;
- x The type and T They're all integer types , Or floating point type ;
- x The type and T They're all plural types ;
- x Is a number or byte/rune The section of ,T by string;
- x yes string type ,T by byte/rune The section of ;
Conversion example description :
*Point(p) // same as *(Point(p))
(*Point)(p) // p is converted to *Point
<-chan int(c) // same as <-(chan int(c))
(<-chan int)(c) // c is converted to <-chan int
func()(x) // function signature func()
(func())(x) // x is converted to func()
(func() int)(x) // x is converted to func() int
func() int(x) // x is converted to func() int (unambiguous)
Types of assertions
Types of assertions (Type Assertion) It is an operation on the interface value , To check whether it implements the desired interface or specific type .
< Value of target type >,< Boolean parameters > := < expression >.( The target type ) // Security type assertion
< Value of target type > := < expression >.( The target type ) // Unsafe type assertion
For type assertions value, ok := x.(T)
, according to ok Judge x Is it T type :
- If T It's a specific type , And assert check x The dynamic type of is T, Then return to x The dynamic value of ( The type is T).
- If T It's the interface type , And the assertion will check x The dynamic type of is T, The return value is of type T The interface value of .
- If x yes nil Interface value , All type assertions fail .
type-switch
adopt type switch Statement can query the real data type of the interface variable :
switch x.(type) {
// cases
}
Determine whether the interface is int or string For example (data.(type)
What you get is data Value , but case What is judged in is its type ; namely v What you get is data value , and switch Type is passed in ):
func VarType(data interface{
}) {
// if v, ok := data.(int); ok{
// fmt.Println("int: ", v)
// result = v
// }else if v, ok := data.(string); ok{
// fmt.Println("string: ", v)
// }else {
// fmt.Printf("%v\n", data)
// }
// Directly through switch-type Judge
switch v := data.(type) {
case int:
fmt.Println("int:", v)
case string:
fmt.Println("string:", v)
default:
fmt.Printf("Default: %v\n", v)
}
}
n := 0
str := "123"
ary := []int{
1,2,3}
VarType(n)
VarType(str)
VarType(ary)
// int: 0
// string: 123
// Default: [1 2 3]
strconv package
strconv The package provides type conversion between strings and simple data types , It mainly includes :
- Append class : Such as AppendBool(dst []byte, b bool)[]byte, Convert the value and add it to []byte At the end of ;
- Format class : take bool/float/int/uint Conversion of type to string(FormatInt The abbreviation of is Itoa); Such as FormatBool(b bool) string;
- Parse class : Convert string to bool/float/int/uint(ParseInt Short for Atoi); Such as ParseBool(str string)(value bool, err error) ,err Identify whether the conversion is successful ;
- Quote class : For strings Double quotes / Single quotation marks / Back single quotes The operation of ;
Strings and numbers
Conversion between integer and string
i, err := strconv.Atoi("-42")
s := strconv.Itoa(-42)
i, err := strconv.ParseInt("-42", 10, 64)
u, err := strconv.ParseUint("42", 10, 64)
s := strconv.FormatInt(-42, 16)
s := strconv.FormatUint(42, 16)
Conversion between Boolean type and string
b, err := strconv.ParseBool("true")
s := strconv.FormatBool(true)
Conversion between floating-point number and string
f, err := strconv.ParseFloat("3.1415", 64)
s := strconv.FormatFloat(3.1415, 'E', -1, 64)
Floating point formatting func FormatFloat(f float64, fmt byte, prec, bitSize int) string
- f: Floating point number to convert
- fmt: Format mark (b、e、E、f、g、G)
- ‘b’ (-ddddp±ddd, Binary index )
- ‘e’ (-d.dddde±dd, Decimal index )
- ‘E’ (-d.ddddE±dd, Decimal index )
- ‘f’ (-ddd.dddd, There is no index )
- ‘g’ ( When the number is large, it is the same ’e’, Otherwise, the same as ’f)
- ‘G’ ( When the number is large, it is the same ’E’, Otherwise, the same as ’f)
- prec: precision
- The format is marked as ‘e’,‘E’ and ’f’: The number of digits after the decimal point ;
- The format is marked as ‘g’,‘G’: Represents the total number of digits ( Integral part + The fractional part );
- bitSize: Specify floating point type (32:float32、64:float64), The result will be rounded accordingly .
quote
Convert the string to the string caused by double quotation marks ( Replace the special string with the transfer character ):
strconv.Quote(`C:\Windows`) // "C:\\Windows"
strconv.QuoteToASCII("Hello The world !") // "Hello \u4e16\u754c\uff01"
Conversion function
The main conversion functions in the package :
- func AppendBool(dst []byte, b bool) []byte
- func AppendFloat(dst []byte, f float64, fmt byte, prec, bitSize int) []byte
- func AppendInt(dst []byte, i int64, base int) []byte
- func AppendQuote(dst []byte, s string) []byte
- func AppendQuoteRune(dst []byte, r rune) []byte
- func AppendQuoteRuneToASCII(dst []byte, r rune) []byte
- func AppendQuoteRuneToGraphic(dst []byte, r rune) []byte
- func AppendQuoteToASCII(dst []byte, s string) []byte
- func AppendQuoteToGraphic(dst []byte, s string) []byte
- func AppendUint(dst []byte, i uint64, base int) []byte
- 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)
- 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) string
- func Unquote(s string) (string, error)
- func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error)
边栏推荐
- Global and Chinese market of full authority digital engine control (FADEC) 2022-2028: Research Report on technology, participants, trends, market size and share
- Micro service knowledge sorting - cache technology
- 2022-06-30 advanced network engineering (XIV) routing strategy - matching tools [ACL, IP prefix list], policy tools [filter policy]
- Global and Chinese market of cyanuric acid 2022-2028: Research Report on technology, participants, trends, market size and share
- Professional interpretation | how to become an SQL developer
- Sword finger offer 30 Stack containing min function
- Use of CMD command
- Leetcode daily question solution: 540 A single element in an ordered array
- 4. Data splitting of Flink real-time project
- Rad+xray vulnerability scanning tool
猜你喜欢
Don't be afraid of no foundation. Zero foundation doesn't need any technology to reinstall the computer system
1.5 learn to find mistakes first
Wargames study notes -- Leviathan
2022-06-27 advanced network engineering (XII) IS-IS overhead type, overhead calculation, LSP processing mechanism, route revocation, route penetration
Exercises of function recursion
1.4 learn more about functions
BOC protected amino acid porphyrins TAPP ala BOC, TAPP Phe BOC, TAPP Trp BOC, Zn · TAPP ala BOC, Zn · TAPP Phe BOC, Zn · TAPP Trp BOC Qiyue
强基计划 数学相关书籍 推荐
Acquisition and transmission of parameters in automatic testing of JMeter interface
FPGA learning notes: vivado 2019.1 project creation
随机推荐
BOC protected tryptophan porphyrin compound (TAPP Trp BOC) Pink Solid 162.8mg supply - Qiyue supply
[raid] [simple DP] mine excavation
Derivation of decision tree theory
Global and Chinese market of liquid antifreeze 2022-2028: Research Report on technology, participants, trends, market size and share
Analysis of gas fee setting under eip1559
Strict data sheet of new features of SQLite 3.37.0
强基计划 数学相关书籍 推荐
Test access criteria
The simplicity of laravel
Global and Chinese market of two in one notebook computers 2022-2028: Research Report on technology, participants, trends, market size and share
Vscode reports an error according to the go plug-in go get connectex: a connection attempt failed because the connected party did not pro
[effective Objective-C] - block and grand central distribution
FAQs for datawhale learning!
11-grom-v2-05-initialization
2.4 conversion of different data types
Microsoft: the 12th generation core processor needs to be upgraded to win11 to give full play to its maximum performance
Oak-d raspberry pie cloud project [with detailed code]
Titles can only be retrieved in PHP via curl - header only retrieval in PHP via curl
Unittest framework is basically used
Bool blind note - score query