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

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

Susan Sarandon
Release: 2024-12-12 13:53:10
Original
698 people have browsed it

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)
Copy after login

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

iAreaId := val.(int)
Copy after login

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

iAreaId, ok := val.(int)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template