These are chat archives for rust-lang/rust

29th
Jan 2019
Tritone
@tritone11
Jan 29 17:15
Hello, sorry for the stupid question, but is it possible to mutate a type of a variable?
I have a case where a variable is a static string, and a if statment where the variable remain a static string, but in the else i need it to become a Vec
Tim Robinson
@1tgr
Jan 29 17:17
You can define an enum type, with a case for a string and a case for a Vec
Ichoran
@Ichoran
Jan 29 17:17
Yes and no. You can rebind the name, but it acts like a new variable that happens to have the same name, not the old variable.
Tritone
@tritone11
Jan 29 17:17
@Ichoran that's the point, I also need it to have the same name
Ichoran
@Ichoran
Jan 29 17:17
Why?

You can always do

let x = "herring";
println!("{}", x);
let x = 7;
println!("{}", x);

but most of the time it's confusing, not helpful.

Tritone
@tritone11
Jan 29 17:18
because I am implementing a little if in a very extensive program
Tim Robinson
@1tgr
Jan 29 17:19
Can you share a bigger example?
Ichoran
@Ichoran
Jan 29 17:19
Sure, but who cares what the name is? What matters is where the content comes from, what type it is, and where it goes to, no? The name is just a way for you to keep track of that stuff.
Tritone
@tritone11
Jan 29 17:19
yes but I cannot do it, because as you said the variable will keep the value before of the if
Ichoran
@Ichoran
Jan 29 17:20
You mean you want to write something like
let mut x = 5;
if iDontLikeFive() {
  let mut x = vec![1, 2, 3, 4];
}
doSomethingSane(x)
If you do that, some of your responses will be Vec<u8> and some will be &str. That seems kind of awkward, even assuming it would compile. Why not make everything be the same type?
For instance, if Vec<u8> is a reasonable type for a response, why not make everything be Vec<u8>?
Tim Robinson
@1tgr
Jan 29 17:23
ciphertext can be Vec<u8> in both cases, if you copy the str
Tritone
@tritone11
Jan 29 17:23
you're right, it was infact a stupid question
:)
Ichoran
@Ichoran
Jan 29 17:24
Alternatively, as @1tgr says, you could make an enum that holds one or the other. (You even could re-use Result for that.) But that just pushes the concerns further along, which probably complicates your code for no great reason.
Tritone
@tritone11
Jan 29 17:25
@Ichoran yes, I don't want to edit the rest of the code, it's just an unsafe implementation for a test
many thanks!
Ichoran
@Ichoran
Jan 29 17:25
Good luck!