GOPROGLIB Telegram 5527
Как проверить, пуст ли интерфейс (interface{}) в Go?

В Go интерфейс считается пустым, только если оба его компонента (динамическое значение и тип) равны nil. Однако есть нюансы, о которых стоит знать.

1️⃣ Прямая проверка с == nil
Если интерфейс действительно пустой (значение и тип nil), проверка if myInterface == nil вернет true.
var i interface{}
if i == nil {
fmt.Println("Интерфейс пустой")
}


2️⃣ Проблема с nil и типом
Если интерфейс содержит nil с типом (например, *int), он не будет считаться пустым.
var i interface{} = (*int)(nil)
if i == nil {
fmt.Println("Пустой") // Не выполнится
} else {
fmt.Println("Не пустой") // Вывод: Не пустой
}


3️⃣ Проверка через reflect
Для точной проверки используйте пакет reflect:
import "reflect"

func isEmptyInterface(i interface{}) bool {
return i == nil || reflect.ValueOf(i).IsZero()
}


💡 Итог:
Используйте if i == nil для простых случаев.
Для значений nil с типом — добавьте проверку через reflect.
Не забывайте, что интерфейс с типом, но nil-значением, не считается пустым.
Please open Telegram to view this post
VIEW IN TELEGRAM
👍213👏2



tgoop.com/goproglib/5527
Create:
Last Update:

Как проверить, пуст ли интерфейс (interface{}) в Go?

В Go интерфейс считается пустым, только если оба его компонента (динамическое значение и тип) равны nil. Однако есть нюансы, о которых стоит знать.

1️⃣ Прямая проверка с == nil
Если интерфейс действительно пустой (значение и тип nil), проверка if myInterface == nil вернет true.

var i interface{}
if i == nil {
fmt.Println("Интерфейс пустой")
}


2️⃣ Проблема с nil и типом
Если интерфейс содержит nil с типом (например, *int), он не будет считаться пустым.
var i interface{} = (*int)(nil)
if i == nil {
fmt.Println("Пустой") // Не выполнится
} else {
fmt.Println("Не пустой") // Вывод: Не пустой
}


3️⃣ Проверка через reflect
Для точной проверки используйте пакет reflect:
import "reflect"

func isEmptyInterface(i interface{}) bool {
return i == nil || reflect.ValueOf(i).IsZero()
}


💡 Итог:
Используйте if i == nil для простых случаев.
Для значений nil с типом — добавьте проверку через reflect.
Не забывайте, что интерфейс с типом, но nil-значением, не считается пустым.

BY Библиотека Go-разработчика | Golang


Share with your friend now:
tgoop.com/goproglib/5527

View MORE
Open in Telegram


Telegram News

Date: |

Joined by Telegram's representative in Brazil, Alan Campos, Perekopsky noted the platform was unable to cater to some of the TSE requests due to the company's operational setup. But Perekopsky added that these requests could be studied for future implementation. The visual aspect of channels is very critical. In fact, design is the first thing that a potential subscriber pays attention to, even though unconsciously. There have been several contributions to the group with members posting voice notes of screaming, yelling, groaning, and wailing in different rhythms and pitches. Calling out the “degenerate” community or the crypto obsessives that engage in high-risk trading, Co-founder of NFT renting protocol Rentable World emiliano.eth shared this group on his Twitter. He wrote: “hey degen, are you stressed? Just let it out all out. Voice only tg channel for screaming”. Telegram channels enable users to broadcast messages to multiple users simultaneously. Like on social media, users need to subscribe to your channel to get access to your content published by one or more administrators. The creator of the channel becomes its administrator by default. If you need help managing your channel, you can add more administrators from your subscriber base. You can provide each admin with limited or full rights to manage the channel. For example, you can allow an administrator to publish and edit content while withholding the right to add new subscribers.
from us


Telegram Библиотека Go-разработчика | Golang
FROM American