CMSC 330: Organization of Programming Languages. Strings, Slices, Vectors, HashMaps in Rust

Similar documents
CMSC 330: Organization of Programming Languages. Ownership, References, and Lifetimes in Rust

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages

1: /////////////// 2: // 1. Basics // 3: /////////////// 4: 5: // Functions. i32 is the type for 32-bit signed integers 6: fn add2(x: i32, y: i32) ->

Programming In Rust. Jim Blandy, / Portland, (Slides are as presented; followup discussion,

CMSC 330: Organization of Programming Languages. Rust Basics

CMSC 330: Organization of Programming Languages

Nicholas Matsakis! Mozilla Research

Rust Advanced Topics

Introduction to Rust 2 / 101

Rust for C++ Programmers

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Introduction to Rust. CC-BY Mozilla. Jonathan Pallant

Next Gen Networking Infrastructure With Rust

Aaron Turon! Mozilla Research

Corrections made in this version not in first posting:

Guaranteeing memory safety in Rust

Rust intro. (for Java Developers) JFokus #jfokus 1. 1

Rust: system programming with guarantees

Next Gen Networking Infrastructure With Rust

Programming in Python

RustBelt: Securing the Foundations of the Rust Programming Language

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CS 11 Ocaml track: lecture 3

Region-based Memory Management. Advanced Operating Systems Lecture 10

Advances in Programming Languages

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Introduction to C++ with content from

Rust. A new systems programming language. 1.0 was released on May 15th. been in development 5+ years. releases every 6 weeks

COMP1730/COMP6730 Programming for Scientists. Strings

Introduction Basics Concurrency Conclusion. Clojure. Marcel Klinzing. December 13, M. Klinzing Clojure 1/18

MUTABLE LISTS AND DICTIONARIES 4

CMSC 330: Organization of Programming Languages. OCaml Data Types

Why you should take a look at

CS1 Lecture 11 Feb. 9, 2018

Iterators & Generators

(CC)A-NC 2.5 by Randall Munroe Python

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

C++11 and Compiler Update

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

CIS192 Python Programming. Robert Rand. August 27, 2015

Memory Management. Advanced Operating Systems (M) Lecture 3

CMSC 330: Organization of Programming Languages

20 Subclassing and Mutation

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Common Programming. Variables and Mutability

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

CMSC 330: Organization of Programming Languages. OCaml Expressions and Functions

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

$ cat ~/.profile GIT_AUTHOR_NAME=Florian Gilcher TWITTER_HANDLE=argorak GITHUB_HANDLE=skade BLOG=skade.

Python Tutorial. Day 1

CS321 Languages and Compiler Design I Winter 2012 Lecture 13

CMSC330 Spring 2016 Midterm #1 9:30am/12:30pm/3:30pm

Quiz 1 Practice Problems

MY GOOD FRIEND RUST. Matthias Endler trivago

CPSC 3740 Programming Languages University of Lethbridge. Data Types

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Sequences and iteration in Python

Programming to Python

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

python 01 September 16, 2016

CMSC330 Spring 2016 Midterm #1 9:30am/12:30pm/3:30pm Solution

Goals of this Lecture

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala

Clojure Concurrency Constructs. CSCI 5828: Foundations of Software Engineering Lecture 12 10/02/2014

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Quiz 1 Solutions. (a) f(n) = n g(n) = log n Circle all that apply: f = O(g) f = Θ(g) f = Ω(g)

B.V. Patel Institute of BMC & IT, UTU 2014

Lecture 23: Priority Queues, Part 2 10:00 AM, Mar 19, 2018

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

CMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection

CS558 Programming Languages. Winter 2013 Lecture 3

Rust for high level applications. Lise Henry

CS527 Software Security

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

Clojure Lisp for the Real clojure.com

CMSC330 Fall 2016 Midterm #1 2:00pm/3:30pm

The fringe of a binary tree are the values in left-to-right order. For example, the fringe of the following tree:

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Lecture #12: Immutable and Mutable Data. Last modified: Mon Feb 22 16:33: CS61A: Lecture #12 1

22c:111 Programming Language Concepts. Fall Types I

Announcements. CSCI 334: Principles of Programming Languages. Lecture 16: Intro to Scala. Announcements. Squeak demo. Instructor: Dan Barowy

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

CMSC330 Spring 2015 Final Exam 9:30am/11:00am/12:30pm

Conversions and Overloading : Overloading

TECHNICAL UNIVERSITY OF MUNICH

Python Programming: Lecture 2 Data Types

Chapter 5. Section 5.4 The Common String Library Functions. CS 50 Hathairat Rattanasook

C2Rust Migrating Legacy Code to Rust

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

Unboxing Sum Types. Johan Tibell - FP-Syd

Unit 2. Srinidhi H Asst Professor

Introduction to Algorithms March 11, 2009 Massachusetts Institute of Technology Spring 2009 Professors Sivan Toledo and Alan Edelman Quiz 1

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

Transcription:

CMSC 330: Organization of Programming Languages Strings, Slices, Vectors, HashMaps in Rust CMSC330 Spring 2018 1

String Representation Rust s String is a 3-tuple A pointer to a byte array (interpreted as UTF-8) A (current) length A (maximum) capacity Always: length capacity String pointed-to data is dropped when the owner is 2

String Representation Rust s String is a 3-tuple A pointer to a byte array (interpreted as UTF-8) A (current) length A (maximum) capacity Always: length capacity let mut s = String::new(); println!("{}", s.capacity()); for _ in 0..5 { s.push_str("hello"); println!("{},{}", s.len(),s.capacity()); } Code Prints 0 5,5 10,10 15,20 20,20 25,40 3

Slices: Motivation Suppose we want the first word of a string. Here s how we might do it in OCaml let first_word s = try let i = String.index s ' ' in String.sub s 0 i with Not_found -> s String.sub allocates new memory and copies the sub-string s contents This is a waste (especially with a large string) if both s and its substring are to be treated as immutable 4

Slice: Shared Data, Separate Metadata What we want is to have both strings share the same underlying data Happily, Rust s containers permit a way to present a slice of an object s contents String String slice 5

String Slices in Rust If s is a String, then &s[range] is a string slice, where range can be as follows. i..j is the range from i to j, inclusive i.. is the range from i to the current length..j is the range from 0 to j.. is the range from 0 to the current length &str is the type of a String slice 6

String Slice Example Here s first_word in Rust, using slices: fn first_word(s: &String) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } 7

Using String Slices A &str slice borrows from the original string Just like an immutable String reference This prevents dangling pointers let mut s = String::from("hello world"); let word = first_word(&s); //borrow s.clear(); // Error! Can t take mut ref String literals are slices let s:&str = "hello world"; Should use slices where possible E.g., fn first_word(s:&str) -> &str Can convert String s to a slice via &s[..]. Oftentimes, this coercion is done automatically (due to Deref trait) 8

Strings Miscellany push_str(&mut self, string: &str) string argument is a slice, so doesn t take ownership, while self is a mutable reference, implying it is the only such reference Iteration over chars, bytes, etc. See also split_at_whitespace Code let s = String::from("hello"); for (i,c) in s.char_indices() { println!("{},{}",i,c); } Prints 0,h 1,e 2,l 3,l 4,o https://doc.rust-lang.org/std/string/struct.string.html 9

Vectors: Basics Vec<T> in Rust is Arraylist<T> in Java { let mut v:vec<i32> = Vec::new(); v.push(1); // adds 1 to v v.push( hi ); //error v contains i32s let w = vec![1, 2, 3]; } // v,w and their elements dropped Indexing can fail (panic) or return an Option let v = vec![1, 2, 3, 4, 5]; let third:&i32 = &v[2]; //panics if OOB let third:option<&i32> = v.get(2); //None if OOB https://doc.rust-lang.org/book/second-edition/ch08-01-vectors.html 10

Aside: Options Option<T> is an enumerated type, like an OCaml variant Some(v) and None are possible values let v = vec![1, 2, 3, 4, 5]; let third:option<&i32> = v.get(2); let z = match v { Some(i) => Some(i+1), //matches here None => None } We ll see more about enumerated types later For now, follow your nose 11

Vectors: Updates and Iteration let mut a = vec![10, 20, 30, 40, 50]; { let p = &mut a[1]; //mutable borrow *p = 2; //updates a[1] }//ownership restored println!("vector contains {:?}",&a); If we remove the {} block around the def of p, above, then the code fails Not allowed to print via a while mutable borrow p is out Iterator variable can be mutable or immutable: let mut v = vec![100, 32, 57]; for i in &v { println!("{}", i); } for i in &mut v { *i += 50; } 12

Vector and Strings Like Strings, vectors can have slices let a = vec![10, 20, 30, 40, 50]; let b = &a[1..3]; //[20,30] let c = &b[1]; //30 println!("{}",c); //prints 30 Strings implemented internally as a Vec<u8> 13

HashMaps HashMap<K,V> has the expected methods (roughly see manual for gory details) new : () -> HashMap<K,V> insert: (K,V) -> Option<V> get : (&K) -> Option<&V> See also get_mut, entry, and or_insert https://doc.rust-lang.org/book/second-edition/ch08-03-hash-maps.html https://doc.rust-lang.org/std/collections/struct.hashmap.html 14