Created
September 28, 2017 14:07
-
-
Save mantyr/d360c9d92dab25d7ef45aa5f379f29ee to your computer and use it in GitHub Desktop.
golang - изменение slice без поинтера на него при инициализации
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Получаем сразу три свойства: | |
1. инициализацию пустым slice по-умолчанию при создании родительской переменной | |
2. возможность добавлять элементы | |
3. возможность навешивать дополнительный функционал | |
package main | |
import ( | |
"fmt" | |
) | |
func main() { | |
cc := C{} | |
cc.A.Add(B("123")) | |
cc.A.Add(B("234")) | |
fmt.Printf("len: %d cap: %d\r\n", len(cc.A), cap(cc.A)) | |
for i := 0; i < 1000; i++ { | |
cc.A.Add("+") // проверяем что размеры slice изменяются | |
} | |
fmt.Printf("%t\r\n", cc) | |
fmt.Printf("len: %d cap: %d\r\n", len(cc.A), cap(cc.A)) | |
} | |
type C struct { | |
Name string | |
A A | |
} | |
type A []B | |
func (a *A) Add(b B) { | |
*a = append(*a, b) | |
} | |
type B string |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment