Why is "const true = false" allowed?

Run a small program:

package main import "fmt" const true = false func main() { if (true == false) { fmt.Println("True equals to false") } fmt.Println("Hello World") } 

https://play.golang.org/p/KwePsmQ_q9

  1. What did you expect to see?

An error or warning message stating that I am creating a constant with an already defined name and potentially violating the entire application.

  1. What did you see instead?

Work without problems. There are no warnings or anything to prevent the creation of a new constant with an already defined name.

+5
source share
1 answer

true and false are not reserved keywords. These are predefined identifiers.

 const ( true = 0 == 0 // Untyped bool. false = 0 != 0 // Untyped bool. ) 

This means that true and false are two simple untyped boolean values. That is why in your example true is false .

https://golang.org/pkg/builtin/#pkg-constants

+9
source

Source: https://habr.com/ru/post/1245611/


All Articles