|
|
Subscribe / Log in / New account

Toward a better list iterator for the kernel

Toward a better list iterator for the kernel

Posted Mar 12, 2022 2:59 UTC (Sat) by droundy (subscriber, #4559)
In reply to: Toward a better list iterator for the kernel by jengelh
Parent article: Toward a better list iterator for the kernel

If C had the ability rust has to create a new variable shadowing the name of a former one, the macro could just create a new variable of a the same name but a different type to make any further use cause a compile error.

But of course if this weren't C we wouldn't have this problem.


to post comments

Toward a better list iterator for the kernel

Posted Mar 12, 2022 17:04 UTC (Sat) by alonz (subscriber, #815) [Link] (2 responses)

Actually in C11 it is possible to create a shadowing variable. However, this usually triggers a compiler warning - since such shadowing is rather confusing to the readers, and is usually considered bad practice (and a harbinger of confusing bugs).

Toward a better list iterator for the kernel

Posted Mar 14, 2022 16:43 UTC (Mon) by laarmen (subscriber, #63948) [Link]

In Rust, variable name re-use is actually rather idiomatic. I used to be skeptical about it, as my experience also was of confusing bugs, or at least code. However, I've embraced this idiom in Rust for purely pragmatic reasons:

In C, your 'char* str' variable will be the same type before and after your null check, but in Rust those are two separate types. A given "content" can undergo multiple type changes in as many lines as the assumptions are checked, it'd be really tedious to have to come up with new names for essentially the same content.

You can find an example of shadowing in the Rust Book in the second chapter! https://doc.rust-lang.org/book/ch02-00-guessing-game-tuto... (the 'guess' name is reused as we go from the raw input string to the actual integer)

Toward a better list iterator for the kernel

Posted Mar 14, 2022 19:51 UTC (Mon) by jem (subscriber, #24231) [Link]

The difference between C and Rust is that Rust allows you reuse a variable name in the same block, which is an error i C.

The scope of a Rust variable variable ends either at the end of the block, or when a new variable with the same name is declared. You can use the old variable when computing the initial value of the new variable, i.e. you can initialize a variable with the value of the variable "itself".

This can be used to change a variable from being mutable to immutable when there is no need to change the value after some point in the program. (Technically there are two separate variables with the same name.)


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds