PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 10, 2022

[FIXED] Why do I need to use &str when defining a string literal in Rust?

 July 10, 2022     reference, rust, string     No comments   

Issue

Why can I not use str here?

let question: &str = "why";

What's the difference between str and &str?

I get that & denotes a reference, but I'm confused about what &str is referencing.


Solution

A str is a sequence of UTF-8 encoded bytes of unknown length, somewhere in memory.

Because its size is not known at compile time, it can't be put on the stack directly, instead, a reference must be used.

A string literal (i.e. the "why" syntax) creates a space in the data segment of the binary, and returns a reference to that location, which is an &str (in particular, an &'static str, because it is never dropped).

If you write let question: str = "why";, this won't compile for the same reason: let i: i32 = &123; won't compile.

P.S. ("hello") is not a tuple, it is just a &str in brackets. If you want to make a tuple with a single element, add a trailing comma: let hello: (&str,) = ("hello",);



Answered By - cameron1024
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing