Why there are not type inference for static/const inside function? I understand why explicit type is required for global - public interface. But inside function? It not consistency with let bindings.
You can have global
It doesn’t make sense. I only meaning inside function inference.
Your question doesn’t make any sense for me.
static require the type to be annotated, everywhere where they are allowed. This is purely consistent.
let has optional types where it is allowed. The type is never required from the parsers view, might the typechecker sometimes asks for it, because its unable to infer it on its own.
static are semantically and syntactically different from
let, therefore, I do not see inconsistencies.
@NobbZ is being kind of harsh here.
@asv1 is asking why
const declared inside a
fn need to have explicit types, noting that they “understand why explicit type is required for global - public interface.” There’s an assumption there: that the reason why
const require explicit types is for clarity of public interface.
If that is the reason why the types are required, then (@asv1 points out) it is strange that the types are required within a
let bindings don’t require them.
However, that assumption isn’t correct. If types were required only to keep public API clear, then we would only need them on
pub static and
pub const – but they are also required on private
static and private
const at the module level.
const inside a
fn are basically the same as private
const at the module level, but they can be written inside a
fn for convenience and smaller scope.
The current rule is easy to teach: const and static always need a type.
Now – the type could be omitted on some
const items, but there is often not enough information to get the types right, because
const are declared in isolation without a lot of context. For example,
const X = 3; // this is not well-typed! const X = 3usize; // this is okay, but it's about as long as... const X: usize = 3; // ...this, which works today.
I haven’t seen anyone propose making the types on
This is not the reason. In particular,
const X = 3; would either be assigned a polymorphic type for types that allow constant literals, or
i32 due to integer fallback (this is more likely).
The main reason for having things the way they are is that
statics are items whereas
let is a statement. Now, you are permitted to have items as statements due to
ast::StmtKind::Item but these items act as if they were top level constructs and are not really part of the function.
There have been suggestions for inference in
statics. Currently there’s https://github.com/rust-lang/rfcs/pull/2545 and previously there was https://github.com/rust-lang/rfcs/pull/2010. Moreover, you can write
const X: &str = "foo"; today which will infer the lifetime