Home >Backend Development >Golang >How to Safely Cast interface{} to int in Go?

How to Safely Cast interface{} to int in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-12 13:53:10688browse

How to Safely Cast interface{} to int in Go?

Casting Interface{} to Int

When extracting a value from JSON and attempting to cast it to an integer, you may encounter an error indicating that an interface{} cannot be directly converted to int. To resolve this, a type assertion is required.

In the provided code example, the line:

iAreaId := int(val)

causes an error because val is an interface{}, which cannot be directly cast to int. Instead, a type assertion is necessary:

iAreaId := val.(int)

This type assertion forcefully casts the value of val to an int. Alternatively, you can use the non-panicking version:

iAreaId, ok := val.(int)

By including the ok variable, you can check if the assertion was successful before proceeding.

Furthermore, it's important to note that explicit conversions can only be performed when the underlying types of the source and destination are compatible, as defined by the Go language specification.

The above is the detailed content of How to Safely Cast interface{} to int in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn