Eli Bendersky has post an interesting article titled
"Does a concrete type implement an interface in Go?"
I really do love seeing C++ experts playing with other languages from their deep understanding of C/C++/Assembly :-)
Go's interface stores embedded data's type information, RTTI in C++, a pointer to v-table minus offset is type information, plus offset are pointers to member functions(index honors declared sequence).
Go's interface stores embedded data act as this pointer in C++, while calling the member functions, copying the embedded data as first parameter into member functions.
Thus, if embedded data is pointer type, then copy the pointer into the member functions.
Alas, if embedded data is instance of the data type, then copy the instance into the member functions.
Go's interface implement:
https://github.com/golang/go/blob/56131cbd1d61ec446e10dfe72a96f329ed3d952a/src/go/types/type.go#L244
Thus, Go's interface type provides an extra layer of abstraction for interface exchanges.
"Does a concrete type implement an interface in Go?"
I really do love seeing C++ experts playing with other languages from their deep understanding of C/C++/Assembly :-)
Go's interface stores embedded data's type information, RTTI in C++, a pointer to v-table minus offset is type information, plus offset are pointers to member functions(index honors declared sequence).
Go's interface stores embedded data act as this pointer in C++, while calling the member functions, copying the embedded data as first parameter into member functions.
Thus, if embedded data is pointer type, then copy the pointer into the member functions.
Alas, if embedded data is instance of the data type, then copy the instance into the member functions.
Go's interface implement:
https://github.com/golang/go/blob/56131cbd1d61ec446e10dfe72a96f329ed3d952a/src/go/types/type.go#L244
Thus, Go's interface type provides an extra layer of abstraction for interface exchanges.
package main import "fmt" type fun struct { } func (f *fun) run() { fmt.Println("stateless member function call.") } type I interface { run() } func main() { I((*fun)(nil)).run() }
C++: https://godbolt.org/z/YWAXze
#include <iostream> struct fun { void run() { using std::cout; using std::endl; cout << "stateless member function call." << endl; } }; int main() { static_cast<fun*>(nullptr)->run(); }
Reference:
A book about the internals of the Go programming language
https://github.com/teh-cmc/go-internals
Go 1.1 Function Calls - Russ Cox, February 2013
https://docs.google.com/document/d/1bMwCey-gmqZVTpRax-ESeVuZGmjwbocYs1iHplK-cjo/pub
Go Data Structures: Interfaces, Russ Cox, December 1, 2009.
https://research.swtch.com/interfaces
Go Interfaces, Ian Lance Taylor
https://www.airs.com/blog/archives/277
[golang] reflection quick note
http://vsdmars.blogspot.com/2019/01/golang-reflection-quick-note.html
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.