Home / Companies / LogRocket / Blog / Post Details
Content Deep Dive

Type assertions vs. type conversions in Go

Blog post from LogRocket

Post Details
Company
Date Published
Author
Ibiyemi Adewakun
Word Count
1,301
Language
-
Hacker News Points
-
Summary

The article provides a detailed exploration of type assertion and type conversion in the Go programming language, emphasizing their distinct uses and operations. Type assertion is used to determine the underlying type of an interface variable, utilizing a syntax of variable.(type) and can prevent errors by using a second value to confirm the type. In contrast, type conversion involves changing a variable from one type to another using a syntax of type(variable), based on the similarity of their data structures, and is demonstrated with examples like converting int to float64. The text also describes how type switching can handle uncertain types by iterating through possible types of an interface variable and highlights that type assertions are applicable only to interfaces, which are essentially definitions of variable methods and attributes. The concept of empty interfaces, which are unspecified until initialization, is explained, alongside examples illustrating how user-defined types can inherit properties from basic types and have unique methods, as seen with the custom type myString.