当前位置:网站首页>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)
边栏推荐
- Oak-d raspberry pie cloud project [with detailed code]
- Wargames study notes -- Leviathan
- Global and Chinese market of speed limiter 2022-2028: Research Report on technology, participants, trends, market size and share
- IP address is such an important knowledge that it's useless to listen to a younger student?
- 4. Data binding
- 7. Data broker presentation
- The 29th day of force deduction (DP topic)
- Derivation of decision tree theory
- Get log4net log file in C - get log4net log file in C
- CesiumJS 2022^ 源码解读[7] - 3DTiles 的请求、加载处理流程解析
猜你喜欢
Geek Daily: the system of monitoring employees' turnover intention has been deeply convinced off the shelves; The meta universe app of wechat and QQ was actively removed from the shelves; IntelliJ pla
CesiumJS 2022^ 源码解读[7] - 3DTiles 的请求、加载处理流程解析
10 smart contract developer tools that miss and lose
Test changes in Devops mode -- learning and thinking
Promethus
Typora charges, WTF? Still need support
Based on laravel 5.5\5.6\5 X solution to the failure of installing laravel ide helper
Meso tetra [P - (p-n-carbazole benzylidene imino)] phenylporphyrin (tcipp) /eu (tcipp) [pc( α- 2-oc8h17) 4] and euh (tcipp) [pc (a-2-oc8h17) 4] supplied by Qiyue
Wechat applet quick start (including NPM package use and mobx status management)
Xctf attack and defense world crypto advanced area best_ rsa
随机推荐
Difference between surface go1 and surface GO2 (non professional comparison)
Ruby replaces gem Alibaba image
2022-07-02 advanced network engineering (XV) routing policy - route policy feature, policy based routing, MQC (modular QoS command line)
Professional interpretation | how to become an SQL developer
2022-06-27 advanced network engineering (XII) IS-IS overhead type, overhead calculation, LSP processing mechanism, route revocation, route penetration
Wargames study notes -- Leviathan
Blue Bridge Cup: the fourth preliminary - "simulated intelligent irrigation system"
Camera calibration (I): robot hand eye calibration
Typora charges, WTF? Still need support
Use of CMD command
CMD implements the language conversion of locale non Unicode programs
Rad+xray vulnerability scanning tool
2022-06-28 advanced network engineering (XIII) IS-IS route filtering, route summary, authentication, factors affecting the establishment of Isis neighbor relations, other commands and characteristics
10 smart contract developer tools that miss and lose
4. Data splitting of Flink real-time project
FAQs for datawhale learning!
QT tutorial: signal and slot mechanism
Meso tetra [P - (p-n-carbazole benzylidene imino)] phenylporphyrin (tcipp) /eu (tcipp) [pc( α- 2-oc8h17) 4] and euh (tcipp) [pc (a-2-oc8h17) 4] supplied by Qiyue
[Yu Yue education] basic reference materials of manufacturing technology of Shanghai Jiaotong University
JMeter connection database