SlideShare ist ein Scribd-Unternehmen logo
1 von 23
Downloaden Sie, um offline zu lesen
Reflection in Go
saifi@acm.org
my Community contribution
Talking
● Networking features
● New 'net' in 1.8
● Reflection
● Channel Internals
● Concurrency with
shared variables
● Working with C code
and plugins
Doing
github.com/golang/go/wiki/Projects
● Lxd
● Juju
● Go-merkle
● Etcd
● Epazote
● Go-kit
● Go-micro
● Prometheus
● llgo
outline
● What is Reflection
● Reflection vs Introspection
● 'reflect' package
● Interesting issues
● Packages using reflection
– Protocol encoding (gob)
– Encode-decode model (json, xml)
– template mechanisms
– Tracing
● Dealing uniformly with values of a type
Reflection
● the ability of a computer program to
– examine and
– modify its own structure and behavior at runtime.
reflect package
● Provides the capability to reflect
● Defines two important types
– Type
– Value
reflect.Type
● A Type represents a golang type.
● It is an interface with multiple methods for
– distinguishing amongst types
– Inspecting the constituent components
● Type descriptors provide information about each
type (it's name and methods)
type Type
func ArrayOf(count int, elem Type) Type
func ChanOf(dir ChanDir, t Type) Type
func FuncOf(in, out []Type, variadic bool) Type
func MapOf(key, elem Type) Type
func PtrTo(t Type) Type
func SliceOf(t Type) Type
func StructOf(fields []StructField) Type
func TypeOf(i interface{}) Type
var w io.Writer
w = os.Stdout
w = new (bytes.Buffer)
w = nil
?
reflect.Type
● reflect.TypeOf() accepts any interface{ } and
returns its dynamic type as a reflect.Type
● Note: assignment from concrete value to interface type
performs implicit interface conversion
type ChanDir
func (d ChanDir) String() string
type Kind
func (k Kind) String() string
type Method
type SelectCase
type SelectDir
type SliceHeader
type StringHeader
type StructField
type StructTag
func (tag StructTag) Get(key string) string
func (tag StructTag) Lookup(key string) (value string, ok bool)
reflect.Value
type Value
func Append(s Value, x ...Value) Value
func AppendSlice(s, t Value) Value
func Indirect(v Value) Value
func MakeChan(typ Type, buffer int) Value
func MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value
func MakeMap(typ Type) Value
func MakeSlice(typ Type, len, cap int) Value
func New(typ Type) Value
func NewAt(typ Type, p unsafe.Pointer) Value
func ValueOf(i interface{}) Value
func Zero(typ Type) Value
● reflect.Value can hold a value of any type.
● reflect.ValueOf() accepts any interface{} and
returns a reflect.Value containing the interface's
dynamic value (aka concrete value)
reflect.Value
type Value
...
func (v Value) Addr() Value
func (v Value) Bool() bool
func (v Value) Bytes() []byte
func (v Value) Call(in []Value) []Value
func (v Value) CallSlice(in []Value) []Value
func (v Value) CanAddr() bool
func (v Value) CanInterface() bool
func (v Value) CanSet() bool
func (v Value) Cap() int
func (v Value) Close()
func (v Value) Complex() complex128
func (v Value) Convert(t Type) Value
func (v Value) Elem() Value
func (v Value) Field(i int) Value
func (v Value) FieldByIndex(index []int) Value
func (v Value) FieldByName(name string) Value
func (v Value) FieldByNameFunc(match func(string) bool) Value
func (v Value) Float() float64
func (v Value) Index(i int) Value
func (v Value) Int() int64
...
reflect.Value
type Value
...
func (v Value) Interface() (i interface{})
func (v Value) InterfaceData() [2]uintptr
func (v Value) IsNil() bool
func (v Value) IsValid() bool
func (v Value) Kind() Kind
func (v Value) Len() int
func (v Value) MapIndex(key Value) Value
func (v Value) MapKeys() []Value
func (v Value) Method(i int) Value
func (v Value) MethodByName(name string) Value
func (v Value) NumField() int
func (v Value) NumMethod() int
...
func (v Value) OverflowComplex(x complex128) bool
func (v Value) OverflowFloat(x float64) bool
func (v Value) OverflowInt(x int64) bool
func (v Value) OverflowUint(x uint64) bool
func (v Value) Pointer() uintptr
func (v Value) Recv() (x Value, ok bool)
func (v Value) Send(x Value)
reflect.Value
type Value
...
func (v Value) Set(x Value)
func (v Value) SetBool(x bool)
func (v Value) SetBytes(x []byte)
func (v Value) SetCap(n int)
func (v Value) SetComplex(x complex128)
func (v Value) SetFloat(x float64)
func (v Value) SetInt(x int64)
func (v Value) SetLen(n int)
func (v Value) SetMapIndex(key, val Value)
func (v Value) SetPointer(x unsafe.Pointer)
func (v Value) SetString(x string)
func (v Value) SetUint(x uint64)
func (v Value) Slice(i, j int) Value
func (v Value) Slice3(i, j, k int) Value
func (v Value) String() string
func (v Value) TryRecv() (x Value, ok bool)
func (v Value) TrySend(x Value) bool
func (v Value) Type() Type
func (v Value) Uint() uint64
func (v Value) UnsafeAddr() uintptr
example show_type
package main
import (
"fmt"
"reflect"
)
func main() {
t := reflect.TypeOf (7)
fmt.Println (t)
fmt.Println (t.String())
}
/* commentary
TypeOf() call assigns the value 7 to the interface{} parameter.
assignment from a concrete value to an interface type performs an implicit conversion
which creates an interface value consisting of two components
. dynamic type (int)
. dynamic value (7)
*/
cf: donovan
Example work with interface
package main
import (
"fmt"
"reflect"
"os"
"io"
)
func main() {
var w io.Writer = os.Stdout
fmt.Println (reflect.TypeOf(w))
}
/* commentary
assignment from a concrete value to an interface type performs an implicit conversion
which creates an interface value consisting of two components
. dynamic type os.Stdout
. dynamic value *os.File not io.Writer.
*/
cf: donovan
Key insight
●
reflect.Type satisfies fmt.Stringer
●
fmt.Printf provides %T that uses
reflect.TypeOf internally.
example set the value of a type
package main
import (
"fmt"
"reflect"
)
func main() {
x :=29
xref := reflect.ValueOf(&x).Elem()
px := xref.Addr().Interface().(*int)
*px = 7
fmt.Println(x)
xref.Set (reflect.ValueOf (99))
fmt.Println(x)
}
code commentary
/*
commentary
. create addressable value by &x
. return inteface dynamic value reflect.ValueOf(&x)
. Elem() returns the value that the interface v contains or that the pointer v points to.
It panics if v's Kind is not Interface or Ptr. It returns the zero Value if v is nil.
. Addr() returns a value holding a pointer to the variable
. Interface() returns interface{} value containing the pointer
. use type assertion to retrieve the contents of the interface
direct
. use reflect.Value.Set()
*/
Some interesting cases
#4876 https://github.com/golang/go/issues/4876
– clarify behavior for unexported names
#5706 https://github.com/golang/go/issues/5706
– field lookup ignores methods that cancel fields
(ambiguity is ignored)
– https://golang.org/src/reflect/type.go#L856
#12918 https://github.com/golang/go/issues/12918
– DeepEqual returns false for equal slices
Encoding / Decoding
● Let's review go source code for
– json code
– encoder
– decoder
–
● Performance comparison
– easyjson
– ffjson
reflection
● Dealing uniformly with values of a type that
– Do not have a common interface
– Do not have a known representation
– Do not exist at the time we design the function
● fmt.Fprintf
References {URL}
● S. Feferman (1962), Transfinite Recursions of
Axiomatic Theories, Journal of Symbolic Logic,
27:259-316, 1962.
Conceptual Paper
● Francois Nicola-Demers, Jacques Malenfant
(1995), Reflection in Logic, Functional and
Object-Oriented programming
https://www-master.ufr-info-p6.jussieu
Comparison with CLR model
● Reflection C++/CLI
https://msdn.microsoft.com/en-us/libra
References {Golang centric}
● Golang 'reflect' package
https://golang.org/pkg/reflect/
● The Laws of Reflection
https://blog.golang.org/laws-of-reflection
● Russ Cox, Representation of interface values
http://research.swtch.com/2009/12/go-data-structure
● Phil Pearl, Anatomy of function call in Go
https://syslog.ravelin.com/anatomy-of-a-function-cal
●
References {json projects}
● easyjson
https://github.com/mailru/easyjson
● ffjson
https://github.com/pquerna/ffjson
● Go lang encoding
https://github.com/golang/go/tree/master/src/encodin
●
Legal { Attribution(s) }
The usage of image is purely for illustrative purposes.
The copyright of each image resides with their respective authors.

Weitere ähnliche Inhalte

Was ist angesagt?

C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
mspline
 

Was ist angesagt? (20)

Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
C++11
C++11C++11
C++11
 
Intro python-object-protocol
Intro python-object-protocolIntro python-object-protocol
Intro python-object-protocol
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
 
The best of AltJava is Xtend
The best of AltJava is XtendThe best of AltJava is Xtend
The best of AltJava is Xtend
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
Type Checking JavaScript
Type Checking JavaScriptType Checking JavaScript
Type Checking JavaScript
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
 
Storage classes in C
Storage classes in CStorage classes in C
Storage classes in C
 
MongoDB.local Berlin: How to add your favorite language to MongoDB Compass
MongoDB.local Berlin: How to add your favorite language to MongoDB CompassMongoDB.local Berlin: How to add your favorite language to MongoDB Compass
MongoDB.local Berlin: How to add your favorite language to MongoDB Compass
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
 
Python-oop
Python-oopPython-oop
Python-oop
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabs
 
Functional go
Functional goFunctional go
Functional go
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 

Andere mochten auch

ぼくのかんがえたさいきょうのうぇぶあぷりけーしょんふれーむわーく - YAPC Asia 2011
ぼくのかんがえたさいきょうのうぇぶあぷりけーしょんふれーむわーく - YAPC Asia 2011ぼくのかんがえたさいきょうのうぇぶあぷりけーしょんふれーむわーく - YAPC Asia 2011
ぼくのかんがえたさいきょうのうぇぶあぷりけーしょんふれーむわーく - YAPC Asia 2011
Hiroh Satoh
 

Andere mochten auch (20)

Go 1.8 'new' networking features
Go 1.8 'new' networking featuresGo 1.8 'new' networking features
Go 1.8 'new' networking features
 
Vogue russia february_2017
Vogue russia february_2017Vogue russia february_2017
Vogue russia february_2017
 
Difference between systematic and unsystematic risk
Difference between systematic and unsystematic riskDifference between systematic and unsystematic risk
Difference between systematic and unsystematic risk
 
Designing realistic medicine
Designing realistic medicineDesigning realistic medicine
Designing realistic medicine
 
ゲームエンジンの歴史概要
ゲームエンジンの歴史概要ゲームエンジンの歴史概要
ゲームエンジンの歴史概要
 
20170311 JAWSDAYS Lunch Session「東急ハンズのiPad POS「HandsPOS」と AWSの付き合い方」
20170311 JAWSDAYS Lunch Session「東急ハンズのiPad POS「HandsPOS」と AWSの付き合い方」20170311 JAWSDAYS Lunch Session「東急ハンズのiPad POS「HandsPOS」と AWSの付き合い方」
20170311 JAWSDAYS Lunch Session「東急ハンズのiPad POS「HandsPOS」と AWSの付き合い方」
 
10 Claves para auto Motivarse
10 Claves para auto Motivarse10 Claves para auto Motivarse
10 Claves para auto Motivarse
 
Chef Robin and Iv-Angelo Interview
Chef Robin and Iv-Angelo InterviewChef Robin and Iv-Angelo Interview
Chef Robin and Iv-Angelo Interview
 
Androidでvulkan事始め
Androidでvulkan事始めAndroidでvulkan事始め
Androidでvulkan事始め
 
Vietnam Digital Landscape - Jan 2017 - We Are Social
Vietnam Digital Landscape - Jan 2017 - We Are SocialVietnam Digital Landscape - Jan 2017 - We Are Social
Vietnam Digital Landscape - Jan 2017 - We Are Social
 
Why do we share news & content on Social Media
Why do we share news & content on Social MediaWhy do we share news & content on Social Media
Why do we share news & content on Social Media
 
MASTERCLASS polypose nasosinusienne Assises ORl de Nice
MASTERCLASS polypose nasosinusienne Assises ORl de NiceMASTERCLASS polypose nasosinusienne Assises ORl de Nice
MASTERCLASS polypose nasosinusienne Assises ORl de Nice
 
DESNUTRICION EN AFRICA
DESNUTRICION EN AFRICADESNUTRICION EN AFRICA
DESNUTRICION EN AFRICA
 
Je suis libre je m'envole dans les airs1
Je suis libre je m'envole dans les airs1Je suis libre je m'envole dans les airs1
Je suis libre je m'envole dans les airs1
 
SIG-Audio#1 CEDEC2012 ラウドネス関連セッション報告
SIG-Audio#1 CEDEC2012 ラウドネス関連セッション報告SIG-Audio#1 CEDEC2012 ラウドネス関連セッション報告
SIG-Audio#1 CEDEC2012 ラウドネス関連セッション報告
 
Octoplus. cambio gerencial avanzado
Octoplus. cambio gerencial avanzadoOctoplus. cambio gerencial avanzado
Octoplus. cambio gerencial avanzado
 
シェーダだけで世界を創る!three.jsによるレイマーチング
シェーダだけで世界を創る!three.jsによるレイマーチングシェーダだけで世界を創る!three.jsによるレイマーチング
シェーダだけで世界を創る!three.jsによるレイマーチング
 
データモデルは時空を越える
データモデルは時空を越えるデータモデルは時空を越える
データモデルは時空を越える
 
ぼくのかんがえたさいきょうのうぇぶあぷりけーしょんふれーむわーく - YAPC Asia 2011
ぼくのかんがえたさいきょうのうぇぶあぷりけーしょんふれーむわーく - YAPC Asia 2011ぼくのかんがえたさいきょうのうぇぶあぷりけーしょんふれーむわーく - YAPC Asia 2011
ぼくのかんがえたさいきょうのうぇぶあぷりけーしょんふれーむわーく - YAPC Asia 2011
 
カヤックにおけるVRのUI/UX
カヤックにおけるVRのUI/UXカヤックにおけるVRのUI/UX
カヤックにおけるVRのUI/UX
 

Ähnlich wie Reflection in Go

FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrong
Julien Wetterwald
 

Ähnlich wie Reflection in Go (20)

Gunosy.go#7 reflect
Gunosy.go#7 reflectGunosy.go#7 reflect
Gunosy.go#7 reflect
 
An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with Swift
 
Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
TDD and mobile development: some forgotten techniques, illustrated with Android
TDD and mobile development: some forgotten techniques, illustrated with AndroidTDD and mobile development: some forgotten techniques, illustrated with Android
TDD and mobile development: some forgotten techniques, illustrated with Android
 
Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016
 
Interpreter Case Study - Design Patterns
Interpreter Case Study - Design PatternsInterpreter Case Study - Design Patterns
Interpreter Case Study - Design Patterns
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrong
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Let's Go-lang
Let's Go-langLet's Go-lang
Let's Go-lang
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
 

Mehr von strikr .

Mehr von strikr . (16)

Monitoring
MonitoringMonitoring
Monitoring
 
OpenStack for Telco Cloud
OpenStack for Telco CloudOpenStack for Telco Cloud
OpenStack for Telco Cloud
 
Oracle to PostgreSQL migration
Oracle to PostgreSQL migrationOracle to PostgreSQL migration
Oracle to PostgreSQL migration
 
DBOps
DBOpsDBOps
DBOps
 
Making Automation Work
Making Automation WorkMaking Automation Work
Making Automation Work
 
Taking the Containers First Approach
Taking the Containers First ApproachTaking the Containers First Approach
Taking the Containers First Approach
 
Docker enterprise Technologies
Docker enterprise TechnologiesDocker enterprise Technologies
Docker enterprise Technologies
 
Data Center to Cloud
Data Center to CloudData Center to Cloud
Data Center to Cloud
 
containerD
containerDcontainerD
containerD
 
from Docker to Moby and back. what changed ?
from Docker to Moby and back. what changed ?from Docker to Moby and back. what changed ?
from Docker to Moby and back. what changed ?
 
OCI Image Spec
OCI Image SpecOCI Image Spec
OCI Image Spec
 
OCI Runtime Spec
OCI Runtime SpecOCI Runtime Spec
OCI Runtime Spec
 
Container Orchestration
Container OrchestrationContainer Orchestration
Container Orchestration
 
cgo and Go plugins
cgo and Go pluginscgo and Go plugins
cgo and Go plugins
 
Referee project
Referee projectReferee project
Referee project
 
Immutable Infrastructure
Immutable InfrastructureImmutable Infrastructure
Immutable Infrastructure
 

Kürzlich hochgeladen

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Kürzlich hochgeladen (20)

Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 

Reflection in Go

  • 2. my Community contribution Talking ● Networking features ● New 'net' in 1.8 ● Reflection ● Channel Internals ● Concurrency with shared variables ● Working with C code and plugins Doing github.com/golang/go/wiki/Projects ● Lxd ● Juju ● Go-merkle ● Etcd ● Epazote ● Go-kit ● Go-micro ● Prometheus ● llgo
  • 3. outline ● What is Reflection ● Reflection vs Introspection ● 'reflect' package ● Interesting issues ● Packages using reflection – Protocol encoding (gob) – Encode-decode model (json, xml) – template mechanisms – Tracing ● Dealing uniformly with values of a type
  • 4. Reflection ● the ability of a computer program to – examine and – modify its own structure and behavior at runtime.
  • 5. reflect package ● Provides the capability to reflect ● Defines two important types – Type – Value
  • 6. reflect.Type ● A Type represents a golang type. ● It is an interface with multiple methods for – distinguishing amongst types – Inspecting the constituent components ● Type descriptors provide information about each type (it's name and methods) type Type func ArrayOf(count int, elem Type) Type func ChanOf(dir ChanDir, t Type) Type func FuncOf(in, out []Type, variadic bool) Type func MapOf(key, elem Type) Type func PtrTo(t Type) Type func SliceOf(t Type) Type func StructOf(fields []StructField) Type func TypeOf(i interface{}) Type var w io.Writer w = os.Stdout w = new (bytes.Buffer) w = nil ?
  • 7. reflect.Type ● reflect.TypeOf() accepts any interface{ } and returns its dynamic type as a reflect.Type ● Note: assignment from concrete value to interface type performs implicit interface conversion type ChanDir func (d ChanDir) String() string type Kind func (k Kind) String() string type Method type SelectCase type SelectDir type SliceHeader type StringHeader type StructField type StructTag func (tag StructTag) Get(key string) string func (tag StructTag) Lookup(key string) (value string, ok bool)
  • 8. reflect.Value type Value func Append(s Value, x ...Value) Value func AppendSlice(s, t Value) Value func Indirect(v Value) Value func MakeChan(typ Type, buffer int) Value func MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value func MakeMap(typ Type) Value func MakeSlice(typ Type, len, cap int) Value func New(typ Type) Value func NewAt(typ Type, p unsafe.Pointer) Value func ValueOf(i interface{}) Value func Zero(typ Type) Value ● reflect.Value can hold a value of any type. ● reflect.ValueOf() accepts any interface{} and returns a reflect.Value containing the interface's dynamic value (aka concrete value)
  • 9. reflect.Value type Value ... func (v Value) Addr() Value func (v Value) Bool() bool func (v Value) Bytes() []byte func (v Value) Call(in []Value) []Value func (v Value) CallSlice(in []Value) []Value func (v Value) CanAddr() bool func (v Value) CanInterface() bool func (v Value) CanSet() bool func (v Value) Cap() int func (v Value) Close() func (v Value) Complex() complex128 func (v Value) Convert(t Type) Value func (v Value) Elem() Value func (v Value) Field(i int) Value func (v Value) FieldByIndex(index []int) Value func (v Value) FieldByName(name string) Value func (v Value) FieldByNameFunc(match func(string) bool) Value func (v Value) Float() float64 func (v Value) Index(i int) Value func (v Value) Int() int64 ...
  • 10. reflect.Value type Value ... func (v Value) Interface() (i interface{}) func (v Value) InterfaceData() [2]uintptr func (v Value) IsNil() bool func (v Value) IsValid() bool func (v Value) Kind() Kind func (v Value) Len() int func (v Value) MapIndex(key Value) Value func (v Value) MapKeys() []Value func (v Value) Method(i int) Value func (v Value) MethodByName(name string) Value func (v Value) NumField() int func (v Value) NumMethod() int ... func (v Value) OverflowComplex(x complex128) bool func (v Value) OverflowFloat(x float64) bool func (v Value) OverflowInt(x int64) bool func (v Value) OverflowUint(x uint64) bool func (v Value) Pointer() uintptr func (v Value) Recv() (x Value, ok bool) func (v Value) Send(x Value)
  • 11. reflect.Value type Value ... func (v Value) Set(x Value) func (v Value) SetBool(x bool) func (v Value) SetBytes(x []byte) func (v Value) SetCap(n int) func (v Value) SetComplex(x complex128) func (v Value) SetFloat(x float64) func (v Value) SetInt(x int64) func (v Value) SetLen(n int) func (v Value) SetMapIndex(key, val Value) func (v Value) SetPointer(x unsafe.Pointer) func (v Value) SetString(x string) func (v Value) SetUint(x uint64) func (v Value) Slice(i, j int) Value func (v Value) Slice3(i, j, k int) Value func (v Value) String() string func (v Value) TryRecv() (x Value, ok bool) func (v Value) TrySend(x Value) bool func (v Value) Type() Type func (v Value) Uint() uint64 func (v Value) UnsafeAddr() uintptr
  • 12. example show_type package main import ( "fmt" "reflect" ) func main() { t := reflect.TypeOf (7) fmt.Println (t) fmt.Println (t.String()) } /* commentary TypeOf() call assigns the value 7 to the interface{} parameter. assignment from a concrete value to an interface type performs an implicit conversion which creates an interface value consisting of two components . dynamic type (int) . dynamic value (7) */ cf: donovan
  • 13. Example work with interface package main import ( "fmt" "reflect" "os" "io" ) func main() { var w io.Writer = os.Stdout fmt.Println (reflect.TypeOf(w)) } /* commentary assignment from a concrete value to an interface type performs an implicit conversion which creates an interface value consisting of two components . dynamic type os.Stdout . dynamic value *os.File not io.Writer. */ cf: donovan
  • 14. Key insight ● reflect.Type satisfies fmt.Stringer ● fmt.Printf provides %T that uses reflect.TypeOf internally.
  • 15. example set the value of a type package main import ( "fmt" "reflect" ) func main() { x :=29 xref := reflect.ValueOf(&x).Elem() px := xref.Addr().Interface().(*int) *px = 7 fmt.Println(x) xref.Set (reflect.ValueOf (99)) fmt.Println(x) }
  • 16. code commentary /* commentary . create addressable value by &x . return inteface dynamic value reflect.ValueOf(&x) . Elem() returns the value that the interface v contains or that the pointer v points to. It panics if v's Kind is not Interface or Ptr. It returns the zero Value if v is nil. . Addr() returns a value holding a pointer to the variable . Interface() returns interface{} value containing the pointer . use type assertion to retrieve the contents of the interface direct . use reflect.Value.Set() */
  • 17. Some interesting cases #4876 https://github.com/golang/go/issues/4876 – clarify behavior for unexported names #5706 https://github.com/golang/go/issues/5706 – field lookup ignores methods that cancel fields (ambiguity is ignored) – https://golang.org/src/reflect/type.go#L856 #12918 https://github.com/golang/go/issues/12918 – DeepEqual returns false for equal slices
  • 18. Encoding / Decoding ● Let's review go source code for – json code – encoder – decoder – ● Performance comparison – easyjson – ffjson
  • 19. reflection ● Dealing uniformly with values of a type that – Do not have a common interface – Do not have a known representation – Do not exist at the time we design the function ● fmt.Fprintf
  • 20. References {URL} ● S. Feferman (1962), Transfinite Recursions of Axiomatic Theories, Journal of Symbolic Logic, 27:259-316, 1962. Conceptual Paper ● Francois Nicola-Demers, Jacques Malenfant (1995), Reflection in Logic, Functional and Object-Oriented programming https://www-master.ufr-info-p6.jussieu Comparison with CLR model ● Reflection C++/CLI https://msdn.microsoft.com/en-us/libra
  • 21. References {Golang centric} ● Golang 'reflect' package https://golang.org/pkg/reflect/ ● The Laws of Reflection https://blog.golang.org/laws-of-reflection ● Russ Cox, Representation of interface values http://research.swtch.com/2009/12/go-data-structure ● Phil Pearl, Anatomy of function call in Go https://syslog.ravelin.com/anatomy-of-a-function-cal ●
  • 22. References {json projects} ● easyjson https://github.com/mailru/easyjson ● ffjson https://github.com/pquerna/ffjson ● Go lang encoding https://github.com/golang/go/tree/master/src/encodin ●
  • 23. Legal { Attribution(s) } The usage of image is purely for illustrative purposes. The copyright of each image resides with their respective authors.