当前位置:网站首页>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
边栏推荐
- Download and configuration of nuitka packaging tutorial
- How mysterious is "PIP not an internal or external command, nor a runnable program or batch file"
- Microsoft Word tutorial, how to insert page numbers and table of contents in word?
- Experience Technology Department of ant group launched the 2023rd school recruitment
- Process creation fork (), demise wait()
- Explain
- 从16页PPT里看懂Jack Dorsey的Web5
- New product launch
- Original introduction to Jenkins' configuration options
- Axure RP 9 for MAC (interactive product prototyping tool) Chinese version
猜你喜欢

今晚7:00 | PhD Debate 自监督学习在推荐系统中的应用

Reading small programs based on wechat e-book graduation design works (7) Interim inspection report

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

Microsoft Word 教程,如何在 Word 中插入页码、目录?

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

负数取余问题
![[generation confrontation network learning III] reading notes of Bigan paper and its principle understanding](/img/6b/0f0815e20cdf6da28793562bcaede1.png)
[generation confrontation network learning III] reading notes of Bigan paper and its principle understanding

Unsupported class file major version 60

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

7 R read / write data
随机推荐
7 R read / write data
Reading small programs based on wechat e-book graduation design works (7) Interim inspection report
Since using low code development, the development efficiency has been increased by 10 times
7:00 tonight | application of PhD debate self supervised learning in Recommendation System
4 R basic exercises
Reading small program based on wechat e-book graduation design (4) opening report
Detailed explanation of IO flow basic knowledge -- file and IO flow principle
Compilation of programs
What did 3GPP ran do in the first F2F meeting?
华尔街备忘单(Wall Street Cheat Sheet)
Understanding of data in memory
The joint empowerment plan of Baidu PaddlePaddle large enterprise open innovation center was launched! Help Pudong to upgrade its industry intelligently
Basic structure of arithmetic unit
Demand and business model innovation - demand 4- overview of demand acquisition
[games101] class note 8 - shading (shading frequency, graphics pipeline, texture mapping)
Are you confused about choosing a low code platform? Follow these three steps
基于微信电子书阅读小程序毕业设计毕设作品(7)中期检查报告
1. Getting to know R
Demand and business model analysis-1-business model canvas
Understand Jack Dorsey's web5 from the ppt on page 16