• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1{{#title std::vector<T> — Rust ♡ C++}}
2# std::vector\<T\>
3
4The Rust binding of std::vector\<T\> is called **[`CxxVector<T>`]**. See the
5link for documentation of the Rust API.
6
7[`CxxVector<T>`]: https://docs.rs/cxx/*/cxx/struct.CxxVector.html
8
9### Restrictions:
10
11Rust code can never obtain a CxxVector by value. Instead in Rust code we will
12only ever look at a vector behind a reference or smart pointer, as in
13&CxxVector\<T\> or UniquePtr\<CxxVector\<T\>\>.
14
15CxxVector\<T\> does not support T being an opaque Rust type. You should use a
16Vec\<T\> (C++ rust::Vec\<T\>) instead for collections of opaque Rust types on
17the language boundary.
18
19## Example
20
21This program involves Rust code converting a `CxxVector<CxxString>` (i.e.
22`std::vector<std::string>`) into a Rust `Vec<String>`.
23
24```rust,noplayground
25// src/main.rs
26
27#![no_main] // main defined in C++ by main.cc
28
29use cxx::{CxxString, CxxVector};
30
31#[cxx::bridge]
32mod ffi {
33    extern "Rust" {
34        fn f(vec: &CxxVector<CxxString>);
35    }
36}
37
38fn f(vec: &CxxVector<CxxString>) {
39    let vec: Vec<String> = vec
40        .iter()
41        .map(|s| s.to_string_lossy().into_owned())
42        .collect();
43    g(&vec);
44}
45
46fn g(vec: &[String]) {
47    println!("{:?}", vec);
48}
49```
50
51```cpp
52// src/main.cc
53
54#include "example/src/main.rs.h"
55#include <string>
56#include <vector>
57
58int main() {
59  std::vector<std::string> vec{"fearless", "concurrency"};
60  f(vec);
61}
62```
63