Tmp: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
(Blanked the page)
Tag: Blanking
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
==Passing Interfaces to Functions==


Interfaces can be used as arguments to functions. Passing an interface instance insures that the function body can rely on the fact the interface methods are available on the passed instance.
With the example above, we declare a function f() that expects an interface A and we pass a B instance when invoking the function:
<pre>
...
type A interface {
    m()
}
func (b B) m() {
    ...
}
func f(a A) {
    a.m()
}
...
b := B{1}
f(b)
...
</pre>
Note that the B instance can be passed by value (as in the example above) or by reference (as in the example below). Both cases work for reasons explained in the [[#Method_Set_associated_with_the_Pointers_of_a_Type|Method Set associated with the Pointers of a Type]] section:
<pre>
...
b := B{1}
f(&b)
...
</pre>
or (same thing)
<pre>
...
bPtr := new(B)
f(bPtr)
...
</pre>
==Interfaces as Fields==
Interfaces can be used as [[Go_Structs#Fields|fields]] in <tt>[[Go_Structs|struct]]</tt>s.
==Implementation Details==
An interface variable is a two-word data structure.
The first word contains a pointer to an internal table called ''iTable'', which contains type information about the stored value: the concrete type of the value that has been stored and a list of methods associated with the value. The second word is a reference to the stored value.
The combination of type information and pointer binds the relationship between the two values.
DEPLETE: [[Go Concepts - The Type System]]

Latest revision as of 22:37, 13 August 2024