Sobes.tech
Middle

Por que a interface vazia em Go pode ser convertida para qualquer tipo?

sobes.tech IA

Resposta da IA

A interface vazia interface{} não contém métodos. Qualquer tipo em Go pode satisfazer uma interface que não requer métodos. Portanto, o valor de qualquer tipo pode ser atribuído a uma variável de tipo interface{} ou passado para uma função que aceita interface{}. Em essência, interface{} é um contêiner para um valor de qualquer tipo, armazenando tanto o valor quanto seu tipo.

package main

import "fmt"

func main() {
	var i interface{} // Declaramos uma variável de interface vazia

	i = 42            // Atribuímos um int
	fmt.Printf("Valor: %v, Tipo: %T\n", i, i)

	i = "olá"        // Atribuímos uma string
	fmt.Printf("Valor: %v, Tipo: %T\n", i, i)

	i = true          // Atribuímos um bool
	fmt.Printf("Valor: %v, Tipo: %T\n", i, i)

	i = struct{}{}    // Atribuímos uma estrutura vazia
	fmt.Printf("Valor: %v, Tipo: %T\n", i, i)
}

A conversão para um tipo específico de interface{} é possível usando afirmação de tipo (type assertion) ou switch de tipo (type switch).

package main

import "fmt"

func main() {
	var i interface{} = "mundo"

	// Afirmação de tipo
	s, ok := i.(string) // Verifica se o valor é uma string
	if ok {
		fmt.Println("Afirmativa de tipo bem-sucedida:", s)
	} else {
		fmt.Println("Falha na afirmação de tipo")
	}

	// Switch de tipo
	switch v := i.(type) {
	case int:
		fmt.Println("O tipo é int, valor:", v)
	case string:
		fmt.Println("O tipo é string, valor:", v)
	default:
		fmt.Println("Tipo desconhecido")
	}
}