当前位置:网站首页>Golang type assertion understanding [go language Bible]
Golang type assertion understanding [go language Bible]
2022-06-12 19:51:00 【Shan Linmin】
Types of assertions
Personal understanding
It took me a long time to understand this thing , Then I use other articles for reference : Go What is a type assertion in a language ?
Although this article for reference does not cover all , Speak through , But let me understand go What is written in the language Bible helps
The key point of my understanding is :
First ,x.(T), x It must be an interface , Interface with 3 Attributes
- Interface dynamic type
- The dynamic value of the interface
- Method collection of interface
Properties of specific types
- type
- Stored values of the corresponding type
- Method ( There may be no way , And types together determine which interfaces are satisfied )
Go Language data types include basic types and compound types .
The basic data types include : Boolean type 、 integer 、 floating-point 、 Plural 、 Character 、 String type 、 Wrong type .
Composite data types include : The pointer 、 Array 、 section 、 Dictionaries 、 passageway 、 Structure 、 Interface .
T Value :
- then T It can be a specific type , Determine whether x Is it this type , If it is , The result of asserting the type is x The dynamic value of ( Properties of the interface ), Its type is T( Properties of specific types )
- If T It's the interface type , The type and interface dynamic value of the interface resulting from the type assertion remain unchanged , A collection of methods for a value change interface ( Through greater )— You can see the following small test
x Value :
If nil, Meeting panic, Of course, if type assertions are used _, ok = x.(T) will ok = false
var k io.Writer
_, ok := k.(io.ByteReader)
fmt.Println(k)
fmt.Println(ok)
// <nil>
// false
go Language Bible text and a little test
A type assertion is an operation used on an interface value . Grammatically, it looks like x.(T) Called assertion types , here x Represents the type of an interface and T Represents a type . A type assertion checks whether the dynamic type of the object it operates on matches the type of the assertion .
There are two possibilities . The first one is , If the type of assertion T It's a specific type , Then type assertion check x Whether the dynamic type of is the same as T identical . If this check is successful , The result of type assertion is x The dynamic value of , Of course, its type is T. let me put it another way , A type assertion of a specific type obtains a specific value from its operand . If the check fails , Next, this operation will throw panic. for example :
var w io.Writer
w = os.Stdout
f := w.(*os.File) // success: f == os.Stdout
c := w.(*bytes.Buffer) // panic: interface holds *os.File, not *bytes.Buffer
The second kind , If the type asserted on the contrary T It's an interface type , Then the type assertion checks whether x The dynamic type of the satisfies T. If this check is successful , Dynamic value not obtained ; The result is still an interface value with the same dynamic type and value part , But the result is type T. let me put it another way , A type assertion on an interface type changes the way the type is expressed , Changed the set of methods that can be obtained ( Usually larger ), But it preserves the dynamic type and value parts inside the interface value .
After the first type assertion below ,w and rw All owned os.Stdout, So they all have a dynamic type *os.File, But variables w It's a io.Writer type , Only the public documents Write Method , and rw The variable also exposes its Read Method .
var w io.Writer
w = os.Stdout
fmt.Printf("%v %T\n", w, w)
rw := w.(io.ReadWriter) // success: *os.File has both Read and Write
fmt.Printf("%v %T\n", w, w)
fmt.Printf("%v %T\n", rw, rw)
w = new(ByteCounter)
rw = w.(io.ReadWriter) // panic: *ByteCounter has no Read method
06/10|10:26:33 test go run str.go
&{0xc0000780c0} *os.File
&{0xc0000780c0} *os.File
&{0xc0000780c0} *os.File
边栏推荐
- The execution results of i+=2 and i++ i++ under synchronized are different
- Blue Bridge Cup basic-14 VIP question time conversion
- Microsoft Word 教程,如何在 Word 中插入页码、目录?
- Wechat e-book reading applet graduation design work (6) opening defense ppt
- IO流基础知识详解--文件及IO流原理
- SPI one master and many slaves
- const
- Demand and business model innovation-5-process
- Basic structure of arithmetic unit
- Explain
猜你喜欢

Wechat e-book reading applet graduation design work (6) opening defense ppt

Negative remainder problem

基于微信电子书阅读小程序毕业设计毕设作品(1)开发概要

Basic structure of arithmetic unit

Using / developing private plug-ins in traifik proxy 2.5 (traifik official blog)

2022年最新宁夏建筑安全员模拟题库及答案

In 2022, 20 cities with the largest number of college students in China

3 R complex data types

Process creation fork (), demise wait()

How to make a computer installation and startup USB flash disk
随机推荐
Programming tool download address
模塊八作業
typescript的装饰器(Decorotor)基本使用
What is a federated index?
Explain
[generation confrontation network learning III] reading notes of Bigan paper and its principle understanding
Stm8l51 sx1280 commissioning record
2 R programming
torch 网络模型转换onnx格式,并可视化
golang类型断言理解[go语言圣经]
Microsoft Word tutorial, how to insert page numbers and table of contents in word?
PostgreSQL数据库复制——后台一等公民进程WalReceiver pg_stat_wal_receiver视图
How do indexes match?
Wechat e-book reading applet graduation design completion works (8) graduation design thesis template
2022年最新宁夏建筑安全员模拟题库及答案
Mode of most elements (map, sort, random, Boyer Moore voting method)
Demand and business model analysis-2-business model types
Equipment management - borrowing / returning module interface code
Promise to solve hell function calls can be used infinitely
easycode一键生成插件自定义模板