当前位置:网站首页>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)
边栏推荐
- Part 27 supplement (27) buttons of QML basic elements
- Micro service knowledge sorting - cache technology
- 2.6 formula calculation
- February 14-20, 2022 (osgear source code debugging +ue4 video +ogremain source code transcription)
- Pat grade B 1009 is ironic (20 points)
- Based on laravel 5.5\5.6\5 X solution to the failure of installing laravel ide helper
- 2166. Design bit set
- Use of aggregate functions
- CesiumJS 2022^ 源码解读[7] - 3DTiles 的请求、加载处理流程解析
- QT tutorial: signal and slot mechanism
猜你喜欢

Nerfplusplus parameter format sorting

PR 2021 quick start tutorial, how to create a new sequence and set parameters?

Exercises of function recursion

Explore the internal mechanism of modern browsers (I) (original translation)

2.3 other data types

10 smart contract developer tools that miss and lose

2022-06-27 advanced network engineering (XII) IS-IS overhead type, overhead calculation, LSP processing mechanism, route revocation, route penetration

Chapter 1: find the algebraic sum of odd factors, find the same decimal sum s (D, n), simplify the same code decimal sum s (D, n), expand the same code decimal sum s (D, n)
![[Yu Yue education] basic reference materials of manufacturing technology of Shanghai Jiaotong University](/img/95/5baf5c8bedb00e67394a6c0a8234ff.png)
[Yu Yue education] basic reference materials of manufacturing technology of Shanghai Jiaotong University

Phpstudy set LAN access
随机推荐
Get log4net log file in C - get log4net log file in C
11-grom-v2-05-initialization
Cesiumjs 2022 ^ source code interpretation [7] - Analysis of the request and loading process of 3dfiles
6006. Take out the minimum number of magic beans
IP address is such an important knowledge that it's useless to listen to a younger student?
Global and Chinese markets of active matrix LCD 2022-2028: Research Report on technology, participants, trends, market size and share
What is the difference between a kill process and a close process- What are the differences between kill process and close process?
5. MVVM model
2.2 integer
App compliance
Fingerprint password lock based on Hal Library
Global and Chinese market of electrolyte analyzers 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese market of charity software 2022-2028: Research Report on technology, participants, trends, market size and share
Initialization and instantiation
It is discussed that the success of Vit lies not in attention. Shiftvit uses the precision of swing transformer to outperform the speed of RESNET
2.3 other data types
2.7 format output of values
5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes
Today's work summary and plan: February 14, 2022
IPv6 experiment