rustref.txt 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. Rust Language Cheat Sheet - https://cheats.rs/
  2. Easy Rust - https://dighomon.github.io/easy_rust/
  3. A Gentle Introduction Rust - https://stevedonovan.github.io/rust-gentle-intro/
  4. Installation - https://doc.rust-lang.org/book/ch01-01-installation.html
  5. The standard library reference - https://doc.rust-lang.org/std/
  6. The rustc book - https://doc.rust-lang.org/stable/rustc/
  7. Cookin' with Rust - https://rust-lang-nursery.github.io/rust-cookbook/
  8. The Embedded Rust Book - https://docs.rust-embedded.org/book/intro/index.html
  9. Learn Rust with Entirely too many Linked Lists -
  10. https://rust-unofficial.github.io/too-many-lists/
  11. The Rust community's crate registry - https://crates.io/
  12. Are we learning yet? - https://www.arewelearningyet.com/
  13. Open-Source Rust crates for numerical simulation - https://www.dimforge.com/
  14. Module ndarray for NumPy users -
  15. https://docs.rs/ndarray/latest/ndarray/doc/ndarray_for_numpy_users/index.html
  16. From Python into Rust -
  17. https://github.com/rochachrumo/py2rs#getting-started-with-rust
  18. Rust quick reference - https://quickref.me/rust
  19. Programming Idioms with Go and Rust -
  20. https://programming-idioms.org/cheatsheet/Go/Rust
  21. Getting started with Programming in Rust -
  22. https://jesselawson.github.io/getting-started-with-rust/
  23. # to download Rustup and install Rust
  24. $ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  25. Rust updates very frequently, if you have installed Rustup some time ago, chances
  26. are your Rust version is out of date. Get the latest version of Rust by running
  27. $ rustup update
  28. # version
  29. $ rustc --version
  30. Rust By Example
  31. $ git clone https://github.com/rust-lang/rust-by-example.git
  32. $ cd rust-by-example
  33. $ cargo install mdbook
  34. $ mdbook build
  35. $ mdbook serve
  36. # list of supported targets
  37. $ rustc --print target-list
  38. # Rust's package manager
  39. $ cargo --help
  40. # list of all avaliable commands
  41. $ cargo --list
  42. # list installed component
  43. $ rustup show
  44. # install component
  45. $ rustup component add clippy
  46. # create new project using cargo
  47. $ cargo new --lib <project> // create new package directory
  48. # create a new Cargo package in an existing directory
  49. $ cargo init // without args creates files in current location
  50. $ cargo init --bin // create a package with a binary target (src/main.rs)
  51. $ cargo init --lib // create a package with a library target (src/lib.rs)
  52. $ cargo init <project> // with <project name> as args acts like cargo new
  53. Ref: https://doc.rust-lang.org/cargo/commands/cargo-init.html
  54. # working on an existing Cargo package
  55. If you download an existing package that uses Cargo, it's really easy to get
  56. going. First, get the package, in this example, we'll use regex cloned from its
  57. repository on GitHub:
  58. $ git clone https://github.com/rust-lang/regex.git
  59. $ cd regex
  60. To build, use cargo build:
  61. $ cargo build
  62. Compiling regex v1.5.0 (file://path/to/package/regex)
  63. This will fetch all of the dependencies and then build them, along with the
  64. package.
  65. Ref: https://doc.rust-lang.org/cargo/guide/working-on-an-existing-project.html
  66. # rust formatting
  67. $ rustfmt program.rs
  68. $ rustfmt lib.rs program.rs
  69. # rust compile
  70. $ rustc program.rs
  71. $ rustc -O program.rs // optimized compile
  72. # adding dependencies using Cargo
  73. Cargo allow to add dependencies that your program needs to run. Adding a
  74. dependency is extremely easy with Cargo. Every Rust package includes a
  75. Cargo.toml file, which contains a list (empty by default) of dependencies. Open
  76. the file, find the [dependencies] section, and add the library you want to
  77. include in your package. For example, to add the rand library as your
  78. dependency.
  79. [dependencies]
  80. rand = "0.3.14"
  81. Try building your package to see what happens.
  82. $ cargo build
  83. New versions of libraries keep coming, and Cargo provides an easy way to update
  84. all of their dependencies using the update command:
  85. $ cargo update
  86. To update specific libraries using the -p flag followed by the package name:
  87. $ cargo update -p rand
  88. # create documnetation
  89. //! # it uses markdown notation
  90. //! - bullet
  91. //! - points
  92. # primitive types
  93. # integers
  94. signed integers: i8, i16, i32, i64, i128, isize
  95. unsigned integers: u8, u16, u32, u64, u128, usize
  96. isize and usize: number of bits on the machine (architecture)
  97. # science in rust lang
  98. ndarray - https://docs.rs/ndarray/latest/ndarray/index.html
  99. nalgebra - https://docs.rs/nalgebra/latest/nalgebra/index.html
  100. plotters - https://plotters-rs.github.io/home/#!/
  101. # don't array but vector
  102. don't pass a variable to a funtion and create an array of that variable size,
  103. instead pass a variable to a function and create a vector ot that variable size.
  104. Example:
  105. Not work:
  106. fn fibonacci(n: usize) -> usize {
  107. let mut f = [0; n]; // create an array of size n and assign 0 (int type)
  108. f[0] = 1; f[1] = 1; // the above line fails since size of n should be a
  109. // constant not a variable for an array creation
  110. for i in 1..n - 1 {
  111. f[i + 1] = f[i] + f[i - 1];
  112. }
  113. return f[n - 1];
  114. }
  115. Work well:
  116. fn fibonacci(n: usize) -> usize {
  117. let mut f = vec![0; n]; // create a vector of size n and assign 0 (int type)
  118. f[0] = 1; f[1] = 1;
  119. for i in 1..n - 1 {
  120. f[i + 1] = f[i] + f[i - 1];
  121. }
  122. return f[n - 1];
  123. }
  124. # comparison between Python and Rust
  125. Python Rust
  126. - interpreted - compiled
  127. - strongly, dynamically typed - strongly and statically typed
  128. - garbage collected - static memory management
  129. - structured, object-oriented, functional - structured, object-oriented, functional, concurrent
  130. - Exceptions - no exceptions
  131. - duck-typing, OO inheritance - no inheritance, uses traits
  132. - v3.0 stable since 2008 - stable since 2015
  133. 00. Hello world
  134. #!/usr/bin/env python
  135. "classic Hello World example in Python" //! classic Hello World example in Rust
  136. if __name__ == '__main__': fn main() {
  137. print("Hello World!") println!("Hello World!");
  138. }
  139. //! - module documentation string
  140. println! - a macro in rust (a function in python)
  141. # ecosystem
  142. Python Rust
  143. linter pylint, pep8 cargo clippy
  144. language server protocal python-language-server RLS, rust-analyzer
  145. code formatting black, yapf, autopep8 cargo fmt
  146. build binary setuptools, py2exe cargo build
  147. test unittest, pytest cargo test
  148. build environment virtualenv, pip, requirements.txt cargo new, cargo update, Cargo.toml
  149. documentation Sphinx based, doxygen cargo doc
  150. benchmark cProfile cargo bench, criterion.rs
  151. # factorial
  152. fn factorial(n: usize) -> usize {
  153. (1..n+1).product()
  154. }
  155. fn main() {
  156. const N: usize = 12;
  157. println!("{}", factorial(N));
  158. }
  159. # prime
  160. fn prime(number: i32) -> String {
  161. /* function to check prime */
  162. let sqrt_number = f64::sqrt(number.into());
  163. for i in 2..(sqrt_number as i32) + 1 {
  164. if number % i == 0 {
  165. return format!("{} is not a prime number", number);
  166. }
  167. }
  168. return format!("{} is a prime number", number);
  169. }
  170. fn main() {
  171. for n in 4..30 {
  172. println!("{}", prime(n));
  173. }
  174. }
  175. # vectors
  176. A vector Vec<T> is a resizable array of elements of type T, allocated on the
  177. heap. There are several ways to create vectors. The simplest is to use the vec!
  178. macro, which gives us a syntax for vectors that looks very much like an array
  179. literal:
  180. let mut primes = vec![2, 3, 5, 7]; // i32 type by default
  181. The vec! macro is equivalent to calling Vec::new to create a new, empty vector
  182. and then pushing the elements onto it, which is another idiom:
  183. let mut pal = Vec::new();
  184. pal.push("step");
  185. pal.push("on");
  186. pal.push("no");
  187. pal.push("pets");
  188. assert_eq!(pal, vec!["step", "on", "no", "pets"]);
  189. Another possibility is to build a vector from the values produced by an
  190. iterator:
  191. let v: Vec<i32> = (0..5).collect();
  192. assert_eq!(v, [0, 1, 2, 3, 4]);
  193. You'll often need to supply the type when using collect (as we've done here),
  194. because it can build many different sorts of collections, not just vectors. By
  195. specifying the type of v, we've made it unambiguous which sort of collection we
  196. want.
  197. The vector's len method returns the number of elements it contains now, its
  198. capacity method returns the number of elements it could hold without
  199. reallocation:
  200. let mut v = Vec::with_capacity(2);
  201. assert_eq!(v.len(), 0);
  202. assert_eq!(v.capacity(), 2);
  203. v.push(1);
  204. v.push(2);
  205. assert_eq!(v.len(), 2);
  206. assert_eq!(v.capacity(), 2);
  207. v.push(3);
  208. assert_eq!(v.len(), 3);
  209. println!("capacity is now {}", v.capacity()); // capacity is now 3
  210. You can insert and remove elements wherever you like in a vector, although these
  211. operations shift all the elements after the affected position forward or
  212. backward, so they may be slow if the vector is long:
  213. let mut v = vec![10, 20, 30, 40, 50];
  214. // make the element at index 3 be 35
  215. v.insert(3, 35);
  216. assert_eq!(v, [10, 20, 30, 35, 40, 50]);
  217. // remove the element at index 1
  218. v.remove(1);
  219. assert_eq!(v, [10, 30, 35, 40, 50]);
  220. You can use the pop method to remove the last element and return it. More
  221. precisely, popping a value from a Vec<T> returns an Option<T>: None if the
  222. vector was already empty, or Some(v) if its last element had been v:
  223. let mut v = vec!["Snow Puff", "Glass Gem"];
  224. assert_eq!(v.pop(), Some("Glass Gem"));
  225. assert_eq!(v.pop(), Some("Snow Puff"));
  226. assert_eq!(v.pop(), None);
  227. # adding all elements in a container
  228. let mut primes = vec![2, 3, 5, 7];
  229. assert_eq!(primes.iter().sum::<i32>(), 17);
  230. primes.push(11);
  231. primes.push(13);
  232. assert_eq!(primes.iter().sum::<i32>(), 41);
  233. # multiply all elements in a container
  234. let mut primes = vec![2, 3, 5, 7];
  235. assert_eq!(primes.iter().product::<i32>(), 210);
  236. primes.push(11);
  237. primes.push(13);
  238. assert_eq!(primes.iter().product::<i32>(), 30030);
  239. # floating-point types
  240. The types f32 and f64 have associated constants for the IEEE-required special
  241. values like INFINITY, NEG_INFINITY (negative infinity), NAN (the not-a-number
  242. value), and MIN and MAX (the largest and smallest finite values):
  243. assert!((-1. / f32::INFINITY).is_sign_negative());
  244. assert_eq!(-f32::MIN, f32::MAX);
  245. The f32 and f64 types provide a full complement of methods for mathematical
  246. calculations; for example, 2f64.sqrt() is the double-precision square root of
  247. two. Some examples:
  248. assert_eq!(5f32.sqrt() * 5f32.sqrt(), 5); // exactly 5.0, per IEEEE
  249. assert_eq!((-1.01f64).floor(), -2.0);
  250. As with integers, you usually won't need to write out type suffixes on
  251. floating-point literals in real code, but when you do, putting a type on either
  252. the literal or the function will suffice.
  253. println!("{}", (2.0_f64).sqrt());
  254. println!("{}", f64::sqrt(2.0));
  255. # math constants
  256. std::f64::consts::PI
  257. # Expressions
  258. Expression type Example Related traits
  259. Addition n + 1 Add
  260. Subtraction n - 1 Sub
  261. Multiplication n * 2 Mul
  262. Division n / 2 Div
  263. Remainder (modulus) n % 2 Rem
  264. Less than n < 1 std::cmp::PartialOrd
  265. Less than or equal n <= 1 std::cmp::PartialOrd
  266. Greater than n > 1 std::cmp::PartialOrd
  267. Greater than or equal n >= 1 std::cmp::PartialOrd
  268. Equal n == 1 std::cmp::PartialEq
  269. Not equal n != 1 std::cmp::PartialEq
  270. Assignment x = val
  271. Compound assignment x += 1 AddAssign
  272. x -= 1 SubAssign
  273. x *= 1 MulAssign
  274. x /= 1 DivAssign
  275. x %= 1 RemAssign
  276. x <<= 1 ShlAssign
  277. x >>= 1 ShrAssign
  278. x &= 1 BitAndAssign
  279. x ^= 1 BitXorAssign
  280. x != 1 BitOrAssign
  281. # ndarray - numpy equivalents
  282. import numpy as np # import numpy library in python
  283. use ndarray::prelude::*; / use the ndarray library in rust
  284. Array creation:
  285. np.array([[1.,2.,3.], [4.,5.,6.]]) # 2x3 floating-point array literal
  286. array![[1.,2.,3.], [4.,5.,6.]] / 2x3 floating-point array literal
  287. arr2(& [[1.,2.,3.], [4.,5.,6.]]) / 2x3 floating-point array literal
  288. np.arange(0., 10., 0.5) # create a 1-D array with values 0., 0.5, ..., 9.5
  289. np.r_[:10.:0.5] # create a 1-D array with values 0., 0.5, ..., 9.5
  290. Array::range(0., 10., 0.5) / create a 1-D array with values 0., 0.5, ..., 9.5
  291. np.linspace(0., 10., 11) # create a 1-D array with 11 elements with values 0., ..., 10.
  292. np.r_[:10.:11] # create a 1-D array with 11 elements with values 0., ..., 10.
  293. Array::linspace(0., 10., 11) / create a 1-D array with 11 elements with values 0., ..., 10.
  294. np.logspace(2.0, 3.0, num=4, base=10.0) # create a 1-D array with 4 elements with values 100., 215.4, 464.1, 1000.
  295. Array::logspace(10.0, 2.0, 3.0, 4) / create a 1-D array with 4 elements with values 100., 215.4, 464.1, 1000.
  296. np.geomspace(1., 1000., num=4) # create a 1-D array with 4 elements with values 1., 10., 100., 1000.
  297. Array::geomspace(1e0, 1e3, 4) / create a 1-D array with 4 elements with values 1., 10., 100., 1000.
  298. np.ones((3, 4, 5)) # create a 3x4x5 array filled with ones (inferring the element type)
  299. Array::ones((3, 4, 5)) / create a 3x4x5 array filled with ones (inferring the element type)
  300. np.zeros((3, 4, 5)) # create a 3x4x5 array filled with zeros (inferring the element type)
  301. Array::zeros((3, 4, 5)) / create a 3x4x5 array filled with zeros (inferring the element type)
  302. np.zeros((3, 4, 5), order='F') # create a 3x4x5 array with Fortran (column-major) memory layout filled with zeros (inferring the element type)
  303. Array::zeros((3, 4, 5).f()) / create a 3x4x5 array with Fortran (column-major) memory layout filled with zeros (inferring the element type)
  304. np.zeros_like(a, order='C') # create an array of zeros of the shape as a, with row-major
  305. Array::zeros(a.raw_dim()) # memory layout (unlike NumPy, this infers the element type from
  306. # context instead of duplicating a's element type)
  307. np.full((3, 4), 7.) # create a 3x4 array filled with the value 7.
  308. Array::from_elem((3, 4), 7.) / create a 3x4 array filled with the value 7.
  309. np.eye(3) # create a 3x3 identity matrix (inferring the element type)
  310. Array::eye(3) / create a 3x3 identity matrix (inferring the element type)
  311. np.diag(np.array([1, 2, 3])) # create a 3x3 matrix with [1, 2, 3] as diagonal and zeros elsewhere (inferring the element type)
  312. Array2::from_diag(&arr1(&[1, 2, 3])) / create a 3x3 matrix with [1, 2, 3] as diagonal and zeros elsewhere (inferring the element type)
  313. np.array([1, 2, 3, 4]).reshape((2, 2)) # create a 2x2 array from the elements in the list/Vec
  314. Array::from_shape_vec((2, 2), vec![1, 2, 3, 4])? / create a 2x2 array from the elements in the list/Vec
  315. np.array([1, 2, 3, 4]).reshape((2, 2), order='F') # create a 2x2 array from the elements in the list/Vec using Fortran (column-major) order
  316. Array::from_shape_vec((2, 2).f(), vec![1, 2, 3, 4])? / create a 2x2 array from the elements in the list/Vec using Fortran (column-major) order
  317. np.random # create arrays of random numbers
  318. Indexing and slicing
  319. a[-1] # access the last element in 1-D array a
  320. a[a.len() - 1] / access the last element in 1-D array a
  321. a[1, 4] # access the element in row 1, column 4
  322. a[[1, 4]] / access the element in row 1, column 4
  323. a[1] # get a 2-D subview of a 3-D array at index 1 of axis 0
  324. a[1, :, :] # get a 2-D subview of a 3-D array at index 1 of axis 0
  325. a.slice(s![1, .., ..]) / get a 2-D subview of a 3-D array at index 1 of axis 0
  326. a.index_axis(Axis(0), 1) / get a 2-D subview of a 3-D array at index 1 of axis 0
  327. a[:5] # get the first 5 rows of a 2-D array
  328. a[0:5] # get the first 5 rows of a 2-D array
  329. a[0:5, :] # get the first 5 rows of a 2-D array
  330. a.slice(s![..5, ..] / get the first 5 rows of a 2-D array
  331. a.slice(s![0..5, ..]) / get the first 5 rows of a 2-D array
  332. a.slice_axis(Axis(0), Slice::from(0..5)) / get the first 5 rows of a 2-D array
  333. a[-5:] # get the last 5 rows of a 2-D array
  334. a[-5:, :] # get the last 5 rows of a 2-D array
  335. a.slice(s![-5.., ..]) / get the last 5 rows of a 2-D array
  336. a.slice_axis(Axis(0), Slice::from(-5..)) / get the last 5 rows of a 2-D array
  337. a[:3, 4:9] # columns 4, 5, 6, 7, and 8 of the first 3 rows
  338. a.slice(s![..3, 4..9]) / columns 4, 5, 6, 7, and 8 of the first 3 rows
  339. a[1:4:2, ::-1] # rows 1 and 3 with the columns in reverse onder
  340. a.slice(s![1..4;2, ..;-1] / rows 1 and 3 with the columns in reverse onder
  341. Shape and strides
  342. np.ndim(a) # get the number of dimensions of array a
  343. a.ndim # get the number of dimensions of array a
  344. a.ndim() / get the number of dimensions of array a
  345. np.size(a) # get the number of elements in array a
  346. a.size # get the number of elements in array a
  347. a.len() / get the number of elements in array a
  348. np.shape(a) # get the shape of array a
  349. a.shape # get the shape of array a
  350. a.shape() / get the shape of array a
  351. a.dim() / get the shape of array a
  352. a.shape[axis] # get the length of an axis
  353. a.len_of(Axis(axis)) / get the length of an axis
  354. a.strides # get the strides of array a
  355. a.strides() / get the strides of array a
  356. np.size(a) == 0 # check if the array has zero elements
  357. a.size == 0 # check if the array has zero elements
  358. a.is_empty() / check if the array has zero elements
  359. Mathematics
  360. a.transpose() # transpose of array a
  361. a.T # transpose of array a
  362. a.t() / transpose of array a
  363. a.reversed_axes() / transpose of array a
  364. mat1.dot(mat2) # 2-D matrix multiply
  365. mat1.dot(&mat2) / 2-D matrix multiply
  366. mat.dot(vec) # 2-D matrix dot 1-D column vector
  367. mat.dot(&vec) / 2-D matrix dot 1-D column vector
  368. vec.dot(mat) # 1-D row vector dot 2-D matrix
  369. vec.dot(&mat) / 1-D row vector dot 2-D matrix
  370. vec1.dot(vec2) # vector dot product
  371. vec1.dot(&vec2) / vector dot product
  372. a * b, a + b, etc. # element-wise arithmetic operations
  373. a * b, a + b, etc. / element-wise arithmetic operations
  374. a**3 # element-wise power of 3
  375. a.mapv(|a| a.powi(3)) / element-wise power of 3
  376. np.sqrt(a) # element-wise square root for f64 array
  377. a.mapv(f64::sqrt) / element-wise square root for f64 array
  378. (a > 0.5) # array of bools of same shape as a with true where a > 0.5 and false elsewhere
  379. a.mapv(|a| a > 0.5) / array of bools of same shape as a with true where a > 0.5 and false elsewhere
  380. np.sum(a) # sum the elements in a
  381. a.sum() # sum the elements in a
  382. a.sum() / sum the elements in a
  383. np.sum(a, axis=2) # sum the elements in a along azis 2
  384. a.sum(axis=2) # sum the elements in a along azis 2
  385. a.sum_axis(Axis(2)) / sum the elements in a along azis 2
  386. np.mean(a) # calculate the mean of the elements in f64 array a
  387. a.mean() # calculate the mean of the elements in f64 array a
  388. a.mean().unwrap() / calculate the mean of the elements in f64 array a
  389. np.mean(a, axis=2) # calculate the mean of the elements in a along axis 2
  390. a.mean(axis=2) # calculate the mean of the elements in a along axis 2
  391. a.mean_axis(Axis(2)) / calculate the mean of the elements in a along axis 2
  392. np.allclose(a, b, atol=1e-8) # check if the arrays' elementwise differences
  393. are within an absolute tolerance (it requires
  394. the approx feature-flag)
  395. a.abs_diff_eq(&b, 1e-8) / check if the arrays' elementwise differences
  396. are within an absolute tolerance (it requires
  397. the approx feature-flag)
  398. np.diag(a) # view the diagonal of a
  399. a.diag() / view the diagonal of a
  400. np.linalg # linear algebra (matrix inverse, solving decompositions, etc.)
  401. Array manipulation
  402. a[:] = 3. # set all array elements to the same scalar value
  403. a.fill(3.) / set all array elements to the same scalar value
  404. a[:] = b # copy the data from array b into array a
  405. a.assign(&b) / copy the data from array b into array a
  406. np.concatenate((a,b), axis=1) # concatenate arrays a and b along axis 1
  407. concatenate![Axis(1), a, b] # concatenate arrays a and b along axis 1
  408. concatenate(Axis(1), &[a.view(), b.view()]) / concatenate arrays a and b along axis 1
  409. np.stack((a,b), axis=1) # stack arrays a and b along axis 1
  410. stack![Axis(1), a, b] / stack arrays a and b along axis 1
  411. stack(Axis(1), vec![a.view(), b.view()]) / stack arrays a and b along axis 1
  412. a[:,np.newaxis] # create an view of 1-D array a, inserting a new axis 1
  413. np.expand_dims(a, axis=1) # create an view of 1-D array a, inserting a new axis 1
  414. a.slice(s![.., NewAxis]) / create an view of 1-D array a, inserting a new axis 1
  415. a.insert_axis(Axis(1)) / create an view of 1-D array a, inserting a new axis 1
  416. a.transpose() # transpose of array a
  417. a.T # transpose of array a
  418. a.t() / transpose of array a
  419. a.reversed_axes() / transpose of array a
  420. np.diag(a) # view the diagonal of a
  421. a.diag() / view the diagonal of a
  422. a.flatten() # create a 1-D array by flattening a
  423. use std::iter::FromIterator;
  424. Array::from_iter(a.iter().cloned()) / create a 1-D array by flattening a
  425. Iteration
  426. a.flat # iterator over the array elements in logical order
  427. a.iter() / iterator over the array elements in logical order
  428. np.ndenumerate(a) # flat iterator yielding the index along with each element reference
  429. a.indexed_iter() / flat iterator yielding the index along with each element reference
  430. iter(a) # iterator over the first (outermost) axis, yielding each subview
  431. a.outer_iter() / iterator over the first (outermost) axis, yielding each subview
  432. a.axis_iter(Axis(0)) / iterator over the first (outermost) axis, yielding each subview
  433. Type conversions
  434. a.astype(np.float32) / convert u8 array infallibly to f32 array with
  435. a.mapv(|x| f32::from(x)) / std::convert::From, generally recommended
  436. a.astype(np.int32) / upcast u8 array to i32 array wit std::convert::From, preferable
  437. a.mapv(|x| i32::from(x)) / over as because it ensures at compile-time that the conversion is lossless
  438. a.astype(np.uint8) / try to convert i8 array to u8 array, panic if any value cannot
  439. a.mapv(|x| u8::try_from(x).unwrap()) / be converted lossless at runtime (e.g. negative value)
  440. a.astype(np.int32) / convert f32 array to i32 array with "saturating" conversion; care needed because
  441. a.mapv(|x| x as i32) / it can be a lossy conversion or result in non-finite values!
  442. Convenience methods for 2-D arrays
  443. len(a) or a.shape[0] # get the number of rows in a 2-D array
  444. a.nrows() / get the number of rows in a 2-D array
  445. a.shape[1] # get the number of columns in a 2-D array
  446. a.ncols() / get the number of columns in a 2-D array
  447. a[1] or a[1,:] # view (or mutable view) of row 1 in a 2-D array
  448. a.row(1) or a.row_mut(1) / view (or mutable view) of row 1 in a 2-D array
  449. a[:,4] # view (or mutable view) of columns 4 in a 2-D array
  450. a.column(4) or a.column_mut(4) / view (or mutable view) of columns 4 in a 2-D array
  451. a.shape[0] == a.shape[1] # check if the array is square
  452. a.is_square() / check if the array is square
  453. Reference: https://docs.rs/ndarray/latest/ndarray/doc/ndarray_for_numpy_users/index.html