3 ms·
Those are two different things. - A _ prefix tells the compiler not to warn you a variable isn't used. - A _ variable name is a reserved symbol to say somethi
by jmyeet 2y ago
Those are two different things.
- A _ prefix tells the compiler not to warn you a variable isn't used.
- A _ variable name is a reserved symbol to say something cannot be used. Trying to do so will cause a compiler error.
So they're scoped differently.
Consider this Go snippet:
func A() { fmt.Println("A") }
func B() { fmt.Println("B") }
func main() {
var B = A;
B()
}
What function gets called? It's A but you can reasonably make a case for B given the capitalization of Go function names and variables. My point is that scoping and resolution rules and many other aspects of a language can be viewed as intuitive (or not) based simply on what you're used to. Even then they can be arbitrary.
- gpderetta 2y agoIn a language where functions are in the same namespace as variables (like the majority of languages), I would expect A, in a lisp-2 I would expect B. But I don't see how's that relevant, this is not about the scope of bindings, but about the lifetime of objects. As Steve explained in a sibling comment, _ is in fact not a variable name, and doesn't extend the lifetime of the object. The semantic is perfectly reasonable and I'm sure it has a good reason to be that way, but the difference between two similarly looking syntaxes is surprising and violates the principle of least astonishment. FWIW, C++ temporary lifetime extensions are also surprising in many cases. [Note: I don't know if rust is defined in term of temporary lifetime extensions, it is just a way to understand it for a c++ programmer like me]
- steveklabnik 2y agoThe definitions are a bit different than in C++ but the overall effect is the same: https://doc.rust-lang.org/stable/reference/expressions.html#temporaries https://doc.rust-lang.org/stable/reference/expressions.html#...
- kazinator 2y agoIf B is called, and the language is otherwise reasonable, then it must mean that there's an A variable in the program which is not showin in the above code. The language must have separate namespaces for functions and variables. But in that case var B = A must be resolving A in the variable namespace; it does not refer to the function A. The local B variable is initialized from some nonlocal A variable, and neither of those are related to the A or B functions, nor have any interaction with the B () call which ignores the variable space, looking up in the function space.