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

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

Mary-Kate Olsen
Release: 2024-12-24 17:16:16
Original
585 people have browsed it

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

Converting interface{} to int in Go

When fetching data from JSON and attempting to cast it to an integer, you may encounter an error stating that you cannot convert an interface{} to an int. This error occurs due to Go's type-assertion rules.

In your code, you have the following line:

iAreaId := int(val)
Copy after login

This line attempts to convert the val, which has the type interface{}, to an int using a type cast. However, type casting an interface{} to an int is not allowed.

To resolve this issue, you need to use a type assertion instead:

iAreaId := val.(int)
Copy after login

A type assertion extracts the underlying value from the interface{} if it has the declared type. If the value does not have the declared type, the type assertion will panic.

Alternatively, you can use a non-panicking version of type assertion using a second return value:

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

The ok variable will be true if the type assertion was successful and false if it was unsuccessful.

By using a type assertion correctly, you can successfully convert an interface{} to an int in Go.

The above is the detailed content of How to Safely Convert 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