33

What does the :: syntax in Rust, as seen here, mean:

fn chunk(n: uint, idx: uint) -> uint {
    let sh = uint::BITS - (SHIFT * (idx + 1));
    (n >> sh) & MASK
}

In languages like Haskell it means a type hint, but here the compiler already has an annotation of that values type, so it seems it's likely type casting.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
heartpunk
  • 2,235
  • 1
  • 21
  • 26

2 Answers2

39

Please review Appendix B: Operators and Symbols of The Rust Programming Language.


In this case, the double colon (::) is the path separator. Paths are comprised of crates, modules, and items.

The full path for your example item, updated for 1.0 is:

std::usize::BITS

Here, std is the crate, usize is a module, and BITS is the specific item — in this case a constant.

If you scroll up in your file, you'll see use core::usize. use adds the path to the set of items to look in. That's how you can get away with just saying usize::BITS. The core crate is an implementation detail of the façade that is the std crate, so you can just substitute std for core in normal code.


:: can also be used as a way to specify generic types when they cannot otherwise be inferred; this is called the turbofish.

See also:

Nate Anderson
  • 18,334
  • 18
  • 100
  • 135
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • The 1-st example [here, documentation for `set` metod of `rlua::Table`](https://docs.rs/rlua/0.9.5/rlua/struct.Table.html) don't seem to be covered by this definition. They create there a variable `lua`, and then do `lua.exec::<()>(r#"…"#, None)`. The `::` doesn't look like a path as in your example. – Hi-Angel Dec 09 '18 at 11:12
  • I asked on IRC: turns out, the `::` syntax is used to supply the `Type` parameter. That's like C++/C#/Java templates, except for some reason there's a redundant double colon. – Hi-Angel Dec 09 '18 at 11:50
  • are these two uses of `::` (path separator & turbofish) related in some way? – joel Aug 03 '19 at 15:28
  • 1
    That turbofish site is cute... :P – basicdays May 16 '20 at 23:08
3

Oops. I wasn't reading very clearly. In this case, it's just the normal way of referring to anything under a module. uint::BITS is a constant, it seems.

heartpunk
  • 2,235
  • 1
  • 21
  • 26