Home > Backend Development > Golang > Go: Type assertions - is there a bug in the specification?

Go: Type assertions - is there a bug in the specification?

WBOY
Release: 2024-02-06 08:35:10
forward
851 people have browsed it

Go:类型断言 - 规范中是否有错误?

Question content

go Are there errors in canonical type assertions?

A type assertion used in an assignment statement or initialization of the special form
v, ok = x.(T)
v, ok := x.(T)
var v, ok = x.(T)
var v, ok interface{} = x.(T) // dynamic types of v and ok are T and bool

yields an additional untyped boolean value.
Copy after login

What is the meaning of the last example? var v, good interface {} = x.(t)?

I'm getting an error in go 1.19 syntax Error: Unexpected interface, expecting := or = or comma


Correct Answer


All these lines are trying the same thing: Type assertion for x to type T. The value ok determines whether the assertion was successful. In the last example you provided, the only difference is that instead of determining the types for v and ok, you provided interface{}## for both # type. Declaring v and ok as interface{} does not change the values ​​they contain. It allows you to send them to a function or add them to a collection that requires an interface{} type, at which point they must be asserted again.

The above is the detailed content of Go: Type assertions - is there a bug in the specification?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template