当前位置:网站首页>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)
边栏推荐
- Implementation of stack
- App compliance
- Test panghu was teaching you how to use the technical code to flirt with girls online on Valentine's Day 520
- JMeter plug-in installation
- JMeter connection database
- Rad+xray vulnerability scanning tool
- 4. Data binding
- Native table - scroll - merge function
- 6006. Take out the minimum number of magic beans
- 2.7 format output of values
猜你喜欢

强基计划 数学相关书籍 推荐

Machine learning support vector machine SVM

IP address is such an important knowledge that it's useless to listen to a younger student?

MPLS configuration

The 29th day of force deduction (DP topic)

2.1 use of variables

Wechat applet quick start (including NPM package use and mobx status management)

Test panghu was teaching you how to use the technical code to flirt with girls online on Valentine's Day 520

原生表格-滚动-合并功能
![How to read the source code [debug and observe the source code]](/img/0d/6495c5da40ed1282803b25746a3f29.jpg)
How to read the source code [debug and observe the source code]
随机推荐
2022 - 06 - 30 networker Advanced (XIV) Routing Policy Matching Tool [ACL, IP prefix list] and policy tool [Filter Policy]
Test panghu was teaching you how to use the technical code to flirt with girls online on Valentine's Day 520
7. Data broker presentation
Print linked list from end to end
About callback function and hook function
Detailed and not wordy. Share the win10 tutorial of computer reinstallation system
Use of aggregate functions
Global and Chinese market of liquid antifreeze 2022-2028: Research Report on technology, participants, trends, market size and share
Microservice framework - frequently asked questions
JMeter connection database
5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes
AST (Abstract Syntax Tree)
How can the outside world get values when using nodejs to link MySQL
Based on laravel 5.5\5.6\5 X solution to the failure of installing laravel ide helper
PR notes:
Plan for the first half of 2022 -- pass the PMP Exam
Commands related to files and directories
Micro service knowledge sorting - three pieces of micro Service Technology
Bright purple crystal meso tetra (4-aminophenyl) porphyrin tapp/tapppt/tappco/tappcd/tappzn/tapppd/tappcu/tappni/tappfe/tappmn metal complex - supplied by Qiyue
HCIA-USG Security Policy