首页 > 其他分享 >[Rust] Reference Types in Rust

[Rust] Reference Types in Rust

时间:2024-02-20 22:47:46浏览次数:31  
标签:name Reference say let Types ref Rust String

Learn how to create references in Rust using the borrow-operator & and when they are useful.

For a more thorough explanation of references and their characteristics, check out this blog post: https://blog.thoughtram.io/references-in-rust/

let name: String = String::from("wzt");
let ref_name: &String = &name; // now refName points to string "wzt"

 

If we use String directly as a param of a function, we will have borrowing problem, for example:

fn main() {
  let name = String::from("wzt");
  let ref_name = &name;

  say_hi(name);
  println!("main {}", name) // Error: borrow of moved value: `name`, value borrowed here after move
}

fn say_hi(name: String) {
  println!("Hello {}!", name)
}

This is because when we pass nameto say_hifunction, say_hifunction owns the name, and when function ends, namewill be destoried. That's why you cannot print name, after say_hifunction call.

 

In order to solve the problem, we can pass by reference:

fn main() {
  let name = String::from("wzt");
  let ref_name = &name;

  say_hi(ref_name);
  println!("main {}", ref_name) // OK

fn say_hi(name: &String) {
  println!("Hello {}!", name)
}

 

标签:name,Reference,say,let,Types,ref,Rust,String
From: https://www.cnblogs.com/Answer1215/p/18024195

相关文章

  • [Rust] Arrays in Rust
    InthislessonwetakealookatArraysandthedifferentwaysofcreatingthem.ArraysinRustarecollectionsofvaluesofthesametypethatcannotchangeinsize.Inotherwords,thenumberoffields(orelements)hastobeknownatcompiletime.#[al......
  • [Rust] Vectors in Rust
    Inthislessonyou'lllearnabout Vec<T>,or Vectors.VectorsarelikeArrays,acollectionofvaluesofthesametype,butasopposedtoArrays,Vectorscanchangeinsize.#[allow(warnings)]fnmain(){letmutnumbers=vec![1,4];......
  • Unity中的SerializeReference使用简介
    Unity默认可以序列化值类型,Serializable属性修饰的类型,派生自UnityEngine.Object的类型,通常这些类型已经足以供日常使用了.但是有时我们希望在编辑器面板上序列化一个接口或者抽象类,则需要用到SerializeReference属性.假定我们有一个接口IEatable,并实现了两个类Brea......
  • rust结构体包含另一个结构体引用时,serde序列化问题
    代码如下useserde::{Deserialize,Serialize};#[derive(Serialize,Deserialize)]structPerson{id:String,name:String,}#[derive(Serialize,Deserialize)]structMsg<'a>{id:String,person:&'aPerson,}fnmain(){......
  • [Rust] Integer Types in Rust
    Thislessontalksabout Integer typesinRustandthatthereare unsigned and signed integers.Italsoexplainshoweverythetypenamesarecomposedof"u"and"i",forunsignedandsignedrespectively,followedbytheir withinbits.......
  • [Rust] parse().unwrap()
    Thislessonexplains TypeInference inRustandhowitallowsthecompilertofigureoutbyitself,whattypevariableshavewhentheygettheirvaluesassigned.Therearecaseswhenthecompilercannotinferavalue'stypethroughstaticanalysis.I......
  • [Rust] Use Impl with Struct
    useanyhow::{Result,anyhow};usestd::str::FromStr;fnget_input()->&'staticstr{return"0,9->5,98,0->0,89,4->3,42,2->2,17,0->7,46,4->2,00,9->2,93,4->1,40,0->8,85,5->8,2&q......
  • typescript修改target导致模块找不到
    编译ts代码时,发现一个包只支持es6及更高的版本,无奈修改编译选项target,从es5修改为es6,发现原来导入包的地方报错,提示notfound。tsconfig.json{"files":["src/main.ts"],"compilerOptions":{"noImplicitAny":true,"target":......
  • 远程控制软件RustDesk自建服务器全平台部署及使用教程
    RustDesk挺出名的一款远程控制,远程协助的开源软件。完美替代TeamViewer,ToDesk,向日葵等平台。关键支持自建服务器,更安全私密远程控制电脑!其中客户端支持安卓,且支持控制安卓手机。官方地址官网:https://rustdesk.com/开源地址:https://github.com/rustdesk/一、准备工作1,有自己......
  • 教你用Rust实现Smpp协议
    本文分享自华为云社区《华为云短信服务教你用Rust实现Smpp协议》,作者:张俭。协议概述SMPP(ShortMessagePeer-to-Peer)协议起源于90年代,最初由Aldiscon公司开发,后来由SMPP开发者论坛维护和推广。SMPP常用于在SMSC(ShortMessageServiceCenter,短信中心)和短信应用之间传输短消息......