Telegram Group & Telegram Channel
💥 Необычное поведение структур

В недавнем блоге Мэтта Холла поднята важная деталь, о которой некоторые забывают.

Автор показывает, что при встраивании (`embedding`) структур Go может выбрать неочевидное поле, даже если кажется, что это вызовет ошибку.

Пример:


type FooService struct { URL string }
type BarConnectionOptions struct { URL string }
type BarService struct { BarConnectionOptions }
type Options struct {
FooService
BarService
}

opts := Options{
FooService: FooService{URL: "abc.com"},
BarService: BarService{
BarConnectionOptions: BarConnectionOptions{URL: "xyz.com"},
},
}
fmt.Println(opts.URL)


Вы думаете, тут компиляция не пройдёт из-за неоднозначности?

Но, она завершится успешна — и начпечатает abc.com.

Go выбирает наименее вложенное поле URL, в данном случае FooService.URL.

Урок: будьте осторожны с struct embedding! Переиспользование полей может скрывать баги, особенно когда поля именованы одинаково, а уровни вложенности различны.

📌 Пост

@golang_google

#golang #go
👍358🔥8🤯3



group-telegram.com/Golang_google/3091
Create:
Last Update:

💥 Необычное поведение структур

В недавнем блоге Мэтта Холла поднята важная деталь, о которой некоторые забывают.

Автор показывает, что при встраивании (`embedding`) структур Go может выбрать неочевидное поле, даже если кажется, что это вызовет ошибку.

Пример:


type FooService struct { URL string }
type BarConnectionOptions struct { URL string }
type BarService struct { BarConnectionOptions }
type Options struct {
FooService
BarService
}

opts := Options{
FooService: FooService{URL: "abc.com"},
BarService: BarService{
BarConnectionOptions: BarConnectionOptions{URL: "xyz.com"},
},
}
fmt.Println(opts.URL)


Вы думаете, тут компиляция не пройдёт из-за неоднозначности?

Но, она завершится успешна — и начпечатает abc.com.

Go выбирает наименее вложенное поле URL, в данном случае FooService.URL.

Урок: будьте осторожны с struct embedding! Переиспользование полей может скрывать баги, особенно когда поля именованы одинаково, а уровни вложенности различны.

📌 Пост

@golang_google

#golang #go

BY Golang





Share with your friend now:
group-telegram.com/Golang_google/3091

View MORE
Open in Telegram


Telegram | DID YOU KNOW?

Date: |

On December 23rd, 2020, Pavel Durov posted to his channel that the company would need to start generating revenue. In early 2021, he added that any advertising on the platform would not use user data for targeting, and that it would be focused on “large one-to-many channels.” He pledged that ads would be “non-intrusive” and that most users would simply not notice any change. Right now the digital security needs of Russians and Ukrainians are very different, and they lead to very different caveats about how to mitigate the risks associated with using Telegram. For Ukrainians in Ukraine, whose physical safety is at risk because they are in a war zone, digital security is probably not their highest priority. They may value access to news and communication with their loved ones over making sure that all of their communications are encrypted in such a manner that they are indecipherable to Telegram, its employees, or governments with court orders. Again, in contrast to Facebook, Google and Twitter, Telegram's founder Pavel Durov runs his company in relative secrecy from Dubai. Elsewhere, version 8.6 of Telegram integrates the in-app camera option into the gallery, while a new navigation bar gives quick access to photos, files, location sharing, and more. Individual messages can be fully encrypted. But the user has to turn on that function. It's not automatic, as it is on Signal and WhatsApp.
from us


Telegram Golang
FROM American