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: |

One thing that Telegram now offers to all users is the ability to “disappear” messages or set remote deletion deadlines. That enables users to have much more control over how long people can access what you’re sending them. Given that Russian law enforcement officials are reportedly (via Insider) stopping people in the street and demanding to read their text messages, this could be vital to protect individuals from reprisals. DFR Lab sent the image through Microsoft Azure's Face Verification program and found that it was "highly unlikely" that the person in the second photo was the same as the first woman. The fact-checker Logically AI also found the claim to be false. The woman, Olena Kurilo, was also captured in a video after the airstrike and shown to have the injuries. And indeed, volatility has been a hallmark of the market environment so far in 2022, with the S&P 500 still down more than 10% for the year-to-date after first sliding into a correction last month. The CBOE Volatility Index, or VIX, has held at a lofty level of more than 30. The S&P 500 fell 1.3% to 4,204.36, and the Dow Jones Industrial Average was down 0.7% to 32,943.33. The Dow posted a fifth straight weekly loss — its longest losing streak since 2019. The Nasdaq Composite tumbled 2.2% to 12,843.81. Though all three indexes opened in the green, stocks took a turn after a new report showed U.S. consumer sentiment deteriorated more than expected in early March as consumers' inflation expectations soared to the highest since 1981. Soloviev also promoted the channel in a post he shared on his own Telegram, which has 580,000 followers. The post recommended his viewers subscribe to "War on Fakes" in a time of fake news.
from us


Telegram Golang
FROM American