In Rust, what kind of syntax is ::<Template>? [duplicate] - rust

I read the below syntax from byteorder:
rdr.read_u16::<BigEndian>()
I can't find any documentation which explains the syntax instance.method::<SomeThing>()

This construct is called turbofish. If you search for this statement, you will discover its definition and its usage.
Although the first edition of The Rust Programming Language is outdated, I feel that this particular section is better than in the second book.
Quoting the second edition:
path::<...>, method::<...>
Specifies parameters to generic type, function, or method in an expression; often referred to as turbofish (e.g., "42".parse::<i32>())
You can use it in any kind of situation where the compiler is not able to deduce the type parameter, e.g.
fn main () {
let a = (0..255).sum();
let b = (0..255).sum::<u32>();
let c: u32 = (0..255).sum();
}
a does not work because it cannot deduce the variable type.
b does work because we specify the type parameter directly with the turbofish syntax.
c does work because we specify the type of c directly.

Related

cfg attribute with arbitrary constant expression

I have the following const:
const IS_WSL: bool = is_wsl!();
and I'd like to be able to use this with the cfg attibute to perform conditional compilation. Something like:
#[cfg(const = "IS_WSL")] // what goes here?
const DOWNLOLADS: &'static str = "/mnt/c/Users/foo/Downloads";
#[cfg(not(const = "IS_WSL"))]
const DOWNLOADS: &'static str = "/home/foo/Downloads";
Obviously this syntax doesn't work, but is there any way to achieve what I'm describing?
I'm aware of custom rustc flags, but would like to avoid doing that, since there's a fair amount of logic that I'd rather not try to write in bash
The answer is not. You have to use something like build script to achieve that.
It cannot work because cfg-expansion occurs at an earlier pass in the compiler than constant evaluation.
cfg expansion works at the same time as macro expansion. Both can affect name resolution (macros can create new names, which other macros, or even the same macro, can later refer to) which forces us to use a fixed-point algorithm (resolve names, expand macros, resolve names, expand macros... until no more names can be resolved, i.e. a fixed point was reached). const evaluation takes a place after type checking, sometimes (with generic_const_exprs) even during codegen. If it could affect macro expansion, we would have a giant fixed-point loop resolve names - expand macros - resolve names - expand macros... until a fixed point is reached, then lower to HIR - type-check - evaluate constants (or even lower to MIR - monomorphize and evaluate constants) - and back to name resolution. Besides slowing the compiler down a lot, it'll also make it significantly more complex, not really something the rustc team wants.
In your specific case, since both cfg variants declare a static with the same name and type you can just match on IS_WSL:
const IS_WSL: bool = is_wsl!();
const DOWNLOADS: &'static str = match IS_WSL {
true => "/mnt/c/Users/foo/Downloads",
false => "/home/foo/Downloads",
};
Playground
This doesn't have the same power as cfg does, but it is still useful if you just need to select two values of the same type.

Where is checksumValid() defined?

I am working from a compliance perspective. I am struggling with the simplest thing, how to find the source for various functions that are called by rustup.
For example, the rustup source code references checksumValid, but I can't find it defined anywhere. I searched stackoverflow, I searched Google, etc.
I'd appreciate help finding checksumValid, but more importantly, what is wrong with my approach?
pub enum Notification<'a> {
...
NoUpdateHash(&'a Path),
ChecksumValid(&'a str),
SignatureValid(&'a str, &'a PgpPublicKey),
...
ChecksumValid(&'a str) here is not actually a function but rather one of many possible values of an enum Notification defined in this line. While the () is usually associated with functions in rust it can denote other things as well. In this case it denotes one possible value of the enum that contains some data that is of type &str with a lifetime of 'a. This is the definition of this value, in this line right here.
You might want to read this to understand the syntax.

No method write found in TcpStream in rust [duplicate]

I tried to compile the following program:
use std::io;
fn main() {
io::stdout().write(b"Please enter your name: ");
io::stdout().flush();
}
Unfortunately, compiler resisted:
error: no method named `write` found for type `std::io::Stdout` in the current scope
--> hello.rs:4:18
|
4 | io::stdout().write(b"Please enter your name: ");
| ^^^^^
|
= help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
= help: candidate #1: `use std::io::Write`
I found that I needed to do use std::io::{self, Write};. What does use std::io; actually do then and how do (if possible) I pull all names defined in std::io? Also, would it be a bad style?
What does use std::io; actually do then?
It does what every use-statement does: makes the last part of the used path directly available (pulling it into the current namespace). That means that you can write io and the compiler knows that you mean std::io.
How do I pull all names defined in std::io?
With use std::io::*;. This is commonly referred to as glob-import.
Also, would it be a bad style?
Yes, it would. Usually you should avoid glob-imports. They can be handy for certain situations, but cause a lot of trouble on most cases. For example, there is also the trait std::fmt::Write... so importing everything from fmt and io would possibly result in name-clashes. Rust values explicitness over implicitness, so rather avoid glob-imports.
However, there is one type of module that is usually used with a glob-import: preludes. And in fact, there is even a std::io::prelude which reexports important symbols. See the documentation for more information.

Python type hints: should I use more generic types?

With Python 3 type hints, should I be using the more generic types as opposed to the more concrete ones? For example
a: Sequence[str] = []
as opposed to:
a: List[str] = []
I'm thinking "yes". Which leads to the question of when would I want to use the more concrete type?
I think I just answered my own question.
I had a Sequence declared like this:
a: Sequence[str] = []
but then I had a need to append items to it. Sequence doesn't have this method defined for it and thus mypy complained. So, I think the answer is "use the generic type by default and drop down to the concrete type when you need to".

How can I declare the Type of a Variable in a Julia Object?

How can I declare a parsimonious type of a variable in the constructor for a object in Julia ? As an example, consider the following:
type DetermineType
foobar::Base.Prod2{LinSpace{Float64},LinSpace{Float64}}
end
function DetermineType(;foo = linspace(0, 1, 10),
bar = linspace(0, 1, 10))
foobar = Base.product(foo, bar)
return DetermineType(foobar)
end
The declaration for foobar isBase.Prod2{LinSpace{Float64},LinSpace{Float64}}. I decided to use this type as it is the output oftypeof(foobar). Whilst this declaration is not yet too long, Base.product with more than two Linspace objects quickly become very verbose. After going through Julia's documentation about Types I think I'm looking for the supertype of foobar. However, I don't know how to obtain it. Can somebody help?
Supertype can be accessed via supertype. In this case, supertype(typeof(foobar)) is a Base.Iterators.AbstractProdIterator.
How much you need to specialize depends on how specialized you need your functionality to be. You can easily end up specializing the type too much. In this case you could perhaps omit the type parameters and just have foobar::Base.Iterators.Prod2.
I'm not sure why the full type is not pretty - it is a very succinct way of describing the type requirement, IF you require the type to be so restricted.

Resources