Thread overview | |||||
---|---|---|---|---|---|
|
August 05, 2020 what's the semantics of 'varX is varY', in particular `strX is strY`? | ||||
---|---|---|---|---|
| ||||
I've thought it's compare by reference, as in e.g. `assert(obj !is null)` but ``` string strX = "2020-07-29"; string strY = "2020-07-29"; string strZ = "2020-07-30"; assert(strX !is strY); // assertion failed assert(strX !is strZ); // assertion pass ``` so here `is` means compare strings by their contents? where is the exact definition of the semantics of 'varX is varY'? BTW, on page: https://dlang.org/spec/lex.html#keywords `is` directly link to: https://dlang.org/spec/expression.html#IsExpression which only talks about is(expr), not 'varX is varY' Thanks. |
August 05, 2020 Re: what's the semantics of 'varX is varY', in particular `strX is strY`? | ||||
---|---|---|---|---|
| ||||
Posted in reply to mw | On Wednesday, 5 August 2020 at 17:29:09 UTC, mw wrote: > so here `is` means compare strings by their contents? They both refer to the same string there... the literal gets reused by the compiler. Put a .dup on one of the strings and then is will not return true anymore. > where is the exact definition of the semantics of 'varX is varY'? It checks if the memory for the variable is the same. |
August 05, 2020 Re: what's the semantics of 'varX is varY', in particular `strX is strY`? | ||||
---|---|---|---|---|
| ||||
Posted in reply to mw | On Wednesday, 5 August 2020 at 17:29:09 UTC, mw wrote: > I've thought it's compare by reference, as in e.g. `assert(obj !is null)` > > but > > ``` > string strX = "2020-07-29"; > string strY = "2020-07-29"; > string strZ = "2020-07-30"; > assert(strX !is strY); // assertion failed > assert(strX !is strZ); // assertion pass > ``` > > so here `is` means compare strings by their contents? where is the exact definition of the semantics of 'varX is varY'? It's documented under the name "Identity Expression": https://dlang.org/spec/expression.html#IdentityExpression You're correct that it's comparing by reference. The reason strX and strY are equal is that the compiler noticed you wrote two identical string literals, so it combined them in the binary. You can tell this is true because `assert(strX.ptr == strY.ptr)` passes. |
Copyright © 1999-2021 by the D Language Foundation