当前位置:首页 > articles > 正文内容

如何重载参考运算符?

Luz4周前 (07-20)articles137

How to overload the reference operator?

  • K. Biermann 问题:
    • I've implemented
      AsRef<[u8]>
      for my type and the automatic conversion to
      &[u8]
      using
      .as_ref()
      works but the
      &
      -operator doesn't... how can I make the operator work?
    • struct Buffer {    data: Vec<u8>,}impl AsRef<[u8]> for Buffer {    fn as_ref(&self) -> &[u8] {        &self.data    }}fn print_slice(slice: &[u8]) {    slice.iter().for_each(|b| print!("{:02x}", b));    println!()}fn main() {    let buffer = Buffer {        data: b"Testolope".to_vec(),    };    // print_slice(&buffer);     // <- This does not work    print_slice(buffer.as_ref()) // <- This works}
    • error[E0308]: mismatched types  --> src/main.rs:20:17   |20 |     print_slice(&buffer);   |                 ^^^^^^^ expected slice, found struct `Buffer`   |   = note: expected type `&[u8]`              found type `&Buffer`
    • I want a generic solution. Other datatypes like
      Vec<u8>
      support the conversion to
      &[u8]
      by using the
      &
      -operator. It would be cool if I could make this work for my own types so that I don't have to use
      .as_ref()
      every time.
  • 回答:
    • stevensonmt - vote: 1
      • You are calling the whole struct with
        print_slice(&buffer);
        but only the
        data
        field with
        print_slice(buffer.as_ref())
        . If you make it
        print_slice(&buffer.data)
        it will work. Alternatively change the type signature of the
        print_slice
        function to expect
        &Buffer
        , which will make the
        as_ref()
        line not work.

相关文章

使用nodejs和mongodb进行前端搜索

Frontend search with nodejs and mongodbCaleb 问题: 我今天刚开始学习mongodb,我有一段代码可以用来查询我的数据库和搜索地址:“Park Lane 38”。这是代码,这是结果:...

应该如何使用kotlin将findViewById传递数据从活动页面写入片段页面

How should write the findViewById pass data to Fragment page from Activity page using kotlinMIN LEE 问题: //这是我的活动页面覆盖...

脚本1 linux中的crear usuarios和demás

Script 1 de crear usuarios y demás en linuxMaría Isabel De la Osa Rocha 问题: Cómo se haría el script del usuario porq...

C++:泛型&gt&gt;如何为一个通用函数定义多个模板解题,该函数充当静态实例创建者

C++:Generics >> How to define several template deklarations for a generic function, which serves as an static inst...

三js如何向FBX模型添加多个没有蒙皮的Mixamo动画?

Three.js how to add multiple Mixamo animations without skin to an FBX model?Anye 问题: I'm trying to create a game whe...

Visual Studio GitHub链接到一个陌生人帐户

Visual Studio GitHub is linked to a stranger accountAhmed Khaldoon 问题: 我从VisualStudio2022(我们称之为divice a)中创建了一个新的私有re...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。