doc: improve embedded struct section (#13574)

pull/13593/head
kahsa 2022-02-23 22:54:00 +09:00 committed by GitHub
parent 114a341f5f
commit 9662b79662
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 7 additions and 20 deletions

View File

@ -2159,10 +2159,7 @@ Button{
}
```
Slightly similar to inheritance, a struct will automatically get all the fields and methods
from its embedded structs.
Unlike inheritance however, you cannot type cast between structs and embedded structs
Unlike inheritance, you cannot type cast between structs and embedded structs
(the embedding struct can also has its own fields, and it can also embed multiple structs).
If you need to access embedded structs directly, use an explicit reference like `button.Size`.
@ -2170,22 +2167,6 @@ If you need to access embedded structs directly, use an explicit reference like
Conceptually, embedded structs are similar to [mixin](https://en.wikipedia.org/wiki/Mixin)s
in OOP, *NOT* base classes.
An embedded structs is responsible for implementing a common structure and exposing a few
functions, just like Lego blocks.
It is not recommended to create a bulky base class with a huge number of fields or functions.
There is no need to import a forest for a banana.
> The problem with object-oriented languages is theyve got all this implicit environment
> that they carry around with them. You wanted a banana but what you got was a gorilla
> holding the banana and the entire jungle.
—— Joe Armstrong, creator of Erlang progamming language
If multiple embedded structs have methods or fields with the same name, or if methods or fields
with the same name are defined in the struct, you can call functions or assign to variables in
the embedded struct like `button.Size.area()`.
You can also initialize an embedded struct:
```v oksyntax
@ -2206,6 +2187,12 @@ button.Size = Size{
}
```
If multiple embedded structs have methods or fields with the same name, or if methods or fields
with the same name are defined in the struct, you can call methods or assign to variables in
the embedded struct like `button.Size.area()`.
When you do not specify the embedded struct name, the method of the outermost struct will be
targeted.
## Unions
Just like structs, unions support embedding.