Roscoe  Batz

Roscoe Batz

1648605600

Create Static Website with Figma & Astro #6: Astro Structure/Component

In this video I will show you how to create a static website with Figma & Astro #6: how to use Astro Structure & Components

🐱‍💻 Access the course files on GitHub:
https://github.com/coding-in-public/desgn-landing-page

#figma #astro 

What is GEEK

Buddha Community

Create Static Website with Figma & Astro #6: Astro Structure/Component
Easter  Deckow

Easter Deckow

1655630160

PyTumblr: A Python Tumblr API v2 Client

PyTumblr

Installation

Install via pip:

$ pip install pytumblr

Install from source:

$ git clone https://github.com/tumblr/pytumblr.git
$ cd pytumblr
$ python setup.py install

Usage

Create a client

A pytumblr.TumblrRestClient is the object you'll make all of your calls to the Tumblr API through. Creating one is this easy:

client = pytumblr.TumblrRestClient(
    '<consumer_key>',
    '<consumer_secret>',
    '<oauth_token>',
    '<oauth_secret>',
)

client.info() # Grabs the current user information

Two easy ways to get your credentials to are:

  1. The built-in interactive_console.py tool (if you already have a consumer key & secret)
  2. The Tumblr API console at https://api.tumblr.com/console
  3. Get sample login code at https://api.tumblr.com/console/calls/user/info

Supported Methods

User Methods

client.info() # get information about the authenticating user
client.dashboard() # get the dashboard for the authenticating user
client.likes() # get the likes for the authenticating user
client.following() # get the blogs followed by the authenticating user

client.follow('codingjester.tumblr.com') # follow a blog
client.unfollow('codingjester.tumblr.com') # unfollow a blog

client.like(id, reblogkey) # like a post
client.unlike(id, reblogkey) # unlike a post

Blog Methods

client.blog_info(blogName) # get information about a blog
client.posts(blogName, **params) # get posts for a blog
client.avatar(blogName) # get the avatar for a blog
client.blog_likes(blogName) # get the likes on a blog
client.followers(blogName) # get the followers of a blog
client.blog_following(blogName) # get the publicly exposed blogs that [blogName] follows
client.queue(blogName) # get the queue for a given blog
client.submission(blogName) # get the submissions for a given blog

Post Methods

Creating posts

PyTumblr lets you create all of the various types that Tumblr supports. When using these types there are a few defaults that are able to be used with any post type.

The default supported types are described below.

  • state - a string, the state of the post. Supported types are published, draft, queue, private
  • tags - a list, a list of strings that you want tagged on the post. eg: ["testing", "magic", "1"]
  • tweet - a string, the string of the customized tweet you want. eg: "Man I love my mega awesome post!"
  • date - a string, the customized GMT that you want
  • format - a string, the format that your post is in. Support types are html or markdown
  • slug - a string, the slug for the url of the post you want

We'll show examples throughout of these default examples while showcasing all the specific post types.

Creating a photo post

Creating a photo post supports a bunch of different options plus the described default options * caption - a string, the user supplied caption * link - a string, the "click-through" url for the photo * source - a string, the url for the photo you want to use (use this or the data parameter) * data - a list or string, a list of filepaths or a single file path for multipart file upload

#Creates a photo post using a source URL
client.create_photo(blogName, state="published", tags=["testing", "ok"],
                    source="https://68.media.tumblr.com/b965fbb2e501610a29d80ffb6fb3e1ad/tumblr_n55vdeTse11rn1906o1_500.jpg")

#Creates a photo post using a local filepath
client.create_photo(blogName, state="queue", tags=["testing", "ok"],
                    tweet="Woah this is an incredible sweet post [URL]",
                    data="/Users/johnb/path/to/my/image.jpg")

#Creates a photoset post using several local filepaths
client.create_photo(blogName, state="draft", tags=["jb is cool"], format="markdown",
                    data=["/Users/johnb/path/to/my/image.jpg", "/Users/johnb/Pictures/kittens.jpg"],
                    caption="## Mega sweet kittens")

Creating a text post

Creating a text post supports the same options as default and just a two other parameters * title - a string, the optional title for the post. Supports markdown or html * body - a string, the body of the of the post. Supports markdown or html

#Creating a text post
client.create_text(blogName, state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")

Creating a quote post

Creating a quote post supports the same options as default and two other parameter * quote - a string, the full text of the qote. Supports markdown or html * source - a string, the cited source. HTML supported

#Creating a quote post
client.create_quote(blogName, state="queue", quote="I am the Walrus", source="Ringo")

Creating a link post

  • title - a string, the title of post that you want. Supports HTML entities.
  • url - a string, the url that you want to create a link post for.
  • description - a string, the desciption of the link that you have
#Create a link post
client.create_link(blogName, title="I like to search things, you should too.", url="https://duckduckgo.com",
                   description="Search is pretty cool when a duck does it.")

Creating a chat post

Creating a chat post supports the same options as default and two other parameters * title - a string, the title of the chat post * conversation - a string, the text of the conversation/chat, with diablog labels (no html)

#Create a chat post
chat = """John: Testing can be fun!
Renee: Testing is tedious and so are you.
John: Aw.
"""
client.create_chat(blogName, title="Renee just doesn't understand.", conversation=chat, tags=["renee", "testing"])

Creating an audio post

Creating an audio post allows for all default options and a has 3 other parameters. The only thing to keep in mind while dealing with audio posts is to make sure that you use the external_url parameter or data. You cannot use both at the same time. * caption - a string, the caption for your post * external_url - a string, the url of the site that hosts the audio file * data - a string, the filepath of the audio file you want to upload to Tumblr

#Creating an audio file
client.create_audio(blogName, caption="Rock out.", data="/Users/johnb/Music/my/new/sweet/album.mp3")

#lets use soundcloud!
client.create_audio(blogName, caption="Mega rock out.", external_url="https://soundcloud.com/skrillex/sets/recess")

Creating a video post

Creating a video post allows for all default options and has three other options. Like the other post types, it has some restrictions. You cannot use the embed and data parameters at the same time. * caption - a string, the caption for your post * embed - a string, the HTML embed code for the video * data - a string, the path of the file you want to upload

#Creating an upload from YouTube
client.create_video(blogName, caption="Jon Snow. Mega ridiculous sword.",
                    embed="http://www.youtube.com/watch?v=40pUYLacrj4")

#Creating a video post from local file
client.create_video(blogName, caption="testing", data="/Users/johnb/testing/ok/blah.mov")

Editing a post

Updating a post requires you knowing what type a post you're updating. You'll be able to supply to the post any of the options given above for updates.

client.edit_post(blogName, id=post_id, type="text", title="Updated")
client.edit_post(blogName, id=post_id, type="photo", data="/Users/johnb/mega/awesome.jpg")

Reblogging a Post

Reblogging a post just requires knowing the post id and the reblog key, which is supplied in the JSON of any post object.

client.reblog(blogName, id=125356, reblog_key="reblog_key")

Deleting a post

Deleting just requires that you own the post and have the post id

client.delete_post(blogName, 123456) # Deletes your post :(

A note on tags: When passing tags, as params, please pass them as a list (not a comma-separated string):

client.create_text(blogName, tags=['hello', 'world'], ...)

Getting notes for a post

In order to get the notes for a post, you need to have the post id and the blog that it is on.

data = client.notes(blogName, id='123456')

The results include a timestamp you can use to make future calls.

data = client.notes(blogName, id='123456', before_timestamp=data["_links"]["next"]["query_params"]["before_timestamp"])

Tagged Methods

# get posts with a given tag
client.tagged(tag, **params)

Using the interactive console

This client comes with a nice interactive console to run you through the OAuth process, grab your tokens (and store them for future use).

You'll need pyyaml installed to run it, but then it's just:

$ python interactive-console.py

and away you go! Tokens are stored in ~/.tumblr and are also shared by other Tumblr API clients like the Ruby client.

Running tests

The tests (and coverage reports) are run with nose, like this:

python setup.py test

Author: tumblr
Source Code: https://github.com/tumblr/pytumblr
License: Apache-2.0 license

#python #api 

Roscoe  Batz

Roscoe Batz

1648605600

Create Static Website with Figma & Astro #6: Astro Structure/Component

In this video I will show you how to create a static website with Figma & Astro #6: how to use Astro Structure & Components

🐱‍💻 Access the course files on GitHub:
https://github.com/coding-in-public/desgn-landing-page

#figma #astro 

Tamale  Moses

Tamale Moses

1669003576

Exploring Mutable and Immutable in Python

In this Python article, let's learn about Mutable and Immutable in Python. 

Mutable and Immutable in Python

Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest definition is: An object whose internal state can be changed is mutable. On the other hand, immutable doesn’t allow any change in the object once it has been created.

Both of these states are integral to Python data structure. If you want to become more knowledgeable in the entire Python Data Structure, take this free course which covers multiple data structures in Python including tuple data structure which is immutable. You will also receive a certificate on completion which is sure to add value to your portfolio.

Mutable Definition

Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability of objects to change their values. These are often the objects that store a collection of data.

Immutable Definition

Immutable is the when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable. Once created, the value of these objects is permanent.

List of Mutable and Immutable objects

Objects of built-in type that are mutable are:

  • Lists
  • Sets
  • Dictionaries
  • User-Defined Classes (It purely depends upon the user to define the characteristics) 

Objects of built-in type that are immutable are:

  • Numbers (Integer, Rational, Float, Decimal, Complex & Booleans)
  • Strings
  • Tuples
  • Frozen Sets
  • User-Defined Classes (It purely depends upon the user to define the characteristics)

Object mutability is one of the characteristics that makes Python a dynamically typed language. Though Mutable and Immutable in Python is a very basic concept, it can at times be a little confusing due to the intransitive nature of immutability.

Objects in Python

In Python, everything is treated as an object. Every object has these three attributes:

  • Identity – This refers to the address that the object refers to in the computer’s memory.
  • Type – This refers to the kind of object that is created. For example- integer, list, string etc. 
  • Value – This refers to the value stored by the object. For example – List=[1,2,3] would hold the numbers 1,2 and 3

While ID and Type cannot be changed once it’s created, values can be changed for Mutable objects.

Check out this free python certificate course to get started with Python.

Mutable Objects in Python

I believe, rather than diving deep into the theory aspects of mutable and immutable in Python, a simple code would be the best way to depict what it means in Python. Hence, let us discuss the below code step-by-step:

#Creating a list which contains name of Indian cities  

cities = [‘Delhi’, ‘Mumbai’, ‘Kolkata’]

# Printing the elements from the list cities, separated by a comma & space

for city in cities:
		print(city, end=’, ’)

Output [1]: Delhi, Mumbai, Kolkata

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(cities)))

Output [2]: 0x1691d7de8c8

#Adding a new city to the list cities

cities.append(‘Chennai’)

#Printing the elements from the list cities, separated by a comma & space 

for city in cities:
	print(city, end=’, ’)

Output [3]: Delhi, Mumbai, Kolkata, Chennai

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(cities)))

Output [4]: 0x1691d7de8c8

The above example shows us that we were able to change the internal state of the object ‘cities’ by adding one more city ‘Chennai’ to it, yet, the memory address of the object did not change. This confirms that we did not create a new object, rather, the same object was changed or mutated. Hence, we can say that the object which is a type of list with reference variable name ‘cities’ is a MUTABLE OBJECT.

Let us now discuss the term IMMUTABLE. Considering that we understood what mutable stands for, it is obvious that the definition of immutable will have ‘NOT’ included in it. Here is the simplest definition of immutable– An object whose internal state can NOT be changed is IMMUTABLE.

Again, if you try and concentrate on different error messages, you have encountered, thrown by the respective IDE; you use you would be able to identify the immutable objects in Python. For instance, consider the below code & associated error message with it, while trying to change the value of a Tuple at index 0. 

#Creating a Tuple with variable name ‘foo’

foo = (1, 2)

#Changing the index[0] value from 1 to 3

foo[0] = 3
	
TypeError: 'tuple' object does not support item assignment 

Immutable Objects in Python

Once again, a simple code would be the best way to depict what immutable stands for. Hence, let us discuss the below code step-by-step:

#Creating a Tuple which contains English name of weekdays

weekdays = ‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’

# Printing the elements of tuple weekdays

print(weekdays)

Output [1]:  (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’)

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(weekdays)))

Output [2]: 0x1691cc35090

#tuples are immutable, so you cannot add new elements, hence, using merge of tuples with the # + operator to add a new imaginary day in the tuple ‘weekdays’

weekdays  +=  ‘Pythonday’,

#Printing the elements of tuple weekdays

print(weekdays)

Output [3]: (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Pythonday’)

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(weekdays)))

Output [4]: 0x1691cc8ad68

This above example shows that we were able to use the same variable name that is referencing an object which is a type of tuple with seven elements in it. However, the ID or the memory location of the old & new tuple is not the same. We were not able to change the internal state of the object ‘weekdays’. The Python program manager created a new object in the memory address and the variable name ‘weekdays’ started referencing the new object with eight elements in it.  Hence, we can say that the object which is a type of tuple with reference variable name ‘weekdays’ is an IMMUTABLE OBJECT.

Also Read: Understanding the Exploratory Data Analysis (EDA) in Python

Where can you use mutable and immutable objects:

Mutable objects can be used where you want to allow for any updates. For example, you have a list of employee names in your organizations, and that needs to be updated every time a new member is hired. You can create a mutable list, and it can be updated easily.

Immutability offers a lot of useful applications to different sensitive tasks we do in a network centred environment where we allow for parallel processing. By creating immutable objects, you seal the values and ensure that no threads can invoke overwrite/update to your data. This is also useful in situations where you would like to write a piece of code that cannot be modified. For example, a debug code that attempts to find the value of an immutable object.

Watch outs:  Non transitive nature of Immutability:

OK! Now we do understand what mutable & immutable objects in Python are. Let’s go ahead and discuss the combination of these two and explore the possibilities. Let’s discuss, as to how will it behave if you have an immutable object which contains the mutable object(s)? Or vice versa? Let us again use a code to understand this behaviour–

#creating a tuple (immutable object) which contains 2 lists(mutable) as it’s elements

#The elements (lists) contains the name, age & gender 

person = (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the tuple

print(person)

Output [1]: (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(person)))

Output [2]: 0x1691ef47f88

#Changing the age for the 1st element. Selecting 1st element of tuple by using indexing [0] then 2nd element of the list by using indexing [1] and assigning a new value for age as 4

person[0][1] = 4

#printing the updated tuple

print(person)

Output [3]: (['Ayaan', 4, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(person)))

Output [4]: 0x1691ef47f88

In the above code, you can see that the object ‘person’ is immutable since it is a type of tuple. However, it has two lists as it’s elements, and we can change the state of lists (lists being mutable). So, here we did not change the object reference inside the Tuple, but the referenced object was mutated.

Also Read: Real-Time Object Detection Using TensorFlow

Same way, let’s explore how it will behave if you have a mutable object which contains an immutable object? Let us again use a code to understand the behaviour–

#creating a list (mutable object) which contains tuples(immutable) as it’s elements

list1 = [(1, 2, 3), (4, 5, 6)]

#printing the list

print(list1)

Output [1]: [(1, 2, 3), (4, 5, 6)]

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(list1)))

Output [2]: 0x1691d5b13c8	

#changing object reference at index 0

list1[0] = (7, 8, 9)

#printing the list

Output [3]: [(7, 8, 9), (4, 5, 6)]

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(list1)))

Output [4]: 0x1691d5b13c8

As an individual, it completely depends upon you and your requirements as to what kind of data structure you would like to create with a combination of mutable & immutable objects. I hope that this information will help you while deciding the type of object you would like to select going forward.

Before I end our discussion on IMMUTABILITY, allow me to use the word ‘CAVITE’ when we discuss the String and Integers. There is an exception, and you may see some surprising results while checking the truthiness for immutability. For instance:
#creating an object of integer type with value 10 and reference variable name ‘x’ 

x = 10
 

#printing the value of ‘x’

print(x)

Output [1]: 10

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(x)))

Output [2]: 0x538fb560

#creating an object of integer type with value 10 and reference variable name ‘y’

y = 10

#printing the value of ‘y’

print(y)

Output [3]: 10

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(y)))

Output [4]: 0x538fb560

As per our discussion and understanding, so far, the memory address for x & y should have been different, since, 10 is an instance of Integer class which is immutable. However, as shown in the above code, it has the same memory address. This is not something that we expected. It seems that what we have understood and discussed, has an exception as well.

Quick check – Python Data Structures

Immutability of Tuple

Tuples are immutable and hence cannot have any changes in them once they are created in Python. This is because they support the same sequence operations as strings. We all know that strings are immutable. The index operator will select an element from a tuple just like in a string. Hence, they are immutable.

Exceptions in immutability

Like all, there are exceptions in the immutability in python too. Not all immutable objects are really mutable. This will lead to a lot of doubts in your mind. Let us just take an example to understand this.

Consider a tuple ‘tup’.

Now, if we consider tuple tup = (‘GreatLearning’,[4,3,1,2]) ;

We see that the tuple has elements of different data types. The first element here is a string which as we all know is immutable in nature. The second element is a list which we all know is mutable. Now, we all know that the tuple itself is an immutable data type. It cannot change its contents. But, the list inside it can change its contents. So, the value of the Immutable objects cannot be changed but its constituent objects can. change its value.

FAQs

1. Difference between mutable vs immutable in Python?

Mutable ObjectImmutable Object
State of the object can be modified after it is created.State of the object can’t be modified once it is created.
They are not thread safe.They are thread safe
Mutable classes are not final.It is important to make the class final before creating an immutable object.

2. What are the mutable and immutable data types in Python?

  • Some mutable data types in Python are:

list, dictionary, set, user-defined classes.

  • Some immutable data types are: 

int, float, decimal, bool, string, tuple, range.

3. Are lists mutable in Python?

Lists in Python are mutable data types as the elements of the list can be modified, individual elements can be replaced, and the order of elements can be changed even after the list has been created.
(Examples related to lists have been discussed earlier in this blog.)

4. Why are tuples called immutable types?

Tuple and list data structures are very similar, but one big difference between the data types is that lists are mutable, whereas tuples are immutable. The reason for the tuple’s immutability is that once the elements are added to the tuple and the tuple has been created; it remains unchanged.

A programmer would always prefer building a code that can be reused instead of making the whole data object again. Still, even though tuples are immutable, like lists, they can contain any Python object, including mutable objects.

5. Are sets mutable in Python?

A set is an iterable unordered collection of data type which can be used to perform mathematical operations (like union, intersection, difference etc.). Every element in a set is unique and immutable, i.e. no duplicate values should be there, and the values can’t be changed. However, we can add or remove items from the set as the set itself is mutable.

6. Are strings mutable in Python?

Strings are not mutable in Python. Strings are a immutable data types which means that its value cannot be updated.

Join Great Learning Academy’s free online courses and upgrade your skills today.


Original article source at: https://www.mygreatlearning.com

#python 

ルヌプを䜿甚しお、Rustのデヌタを反埩凊理したす

このモゞュヌルでは、Rustでハッシュマップ耇合デヌタ型を操䜜する方法に぀いお説明したす。ハッシュマップのようなコレクション内のデヌタを反埩凊理するルヌプ匏を実装する方法を孊びたす。挔習ずしお、芁求された泚文をルヌプし、条件をテストし、さたざたなタむプのデヌタを凊理するこずによっお車を䜜成するRustプログラムを䜜成したす。

さび遊び堎

錆遊び堎は錆コンパむラにブラりザむンタフェヌスです。蚀語をロヌカルにむンストヌルする前、たたはコンパむラが利甚できない堎合は、Playgroundを䜿甚しおRustコヌドの蚘述を詊すこずができたす。このコヌス党䜓を通しお、サンプルコヌドず挔習ぞのPlaygroundリンクを提䟛したす。珟時点でRustツヌルチェヌンを䜿甚できない堎合でも、コヌドを操䜜できたす。

Rust Playgroundで実行されるすべおのコヌドは、ロヌカルの開発環境でコンパむルしお実行するこずもできたす。コンピュヌタヌからRustコンパむラヌず察話するこずを躊躇しないでください。Rust Playgroundの詳现に぀いおは、What isRustをご芧ください。モゞュヌル。

孊習目暙

このモゞュヌルでは、次のこずを行いたす。

  • Rustのハッシュマップデヌタ型、およびキヌず倀にアクセスする方法を確認しおください
  • ルヌプ匏を䜿甚しおRustプログラムのデヌタを反埩凊理する方法を探る
  • Rustプログラムを䜜成、コンパむル、実行しお、ルヌプを䜿甚しおハッシュマップデヌタを反埩凊理したす

Rustのもう1぀の䞀般的なコレクションの皮類は、ハッシュマップです。このHashMap<K, V>型は、各キヌKをその倀にマッピングするこずによっおデヌタを栌玍したすV。ベクトル内のデヌタは敎数むンデックスを䜿甚しおアクセスされたすが、ハッシュマップ内のデヌタはキヌを䜿甚しおアクセスされたす。

ハッシュマップタむプは、オブゞェクト、ハッシュテヌブル、蟞曞などのデヌタ項目の倚くのプログラミング蚀語で䜿甚されたす。

ベクトルのように、ハッシュマップは拡匵可胜です。デヌタはヒヌプに栌玍され、ハッシュマップアむテムぞのアクセスは実行時にチェックされたす。

ハッシュマップを定矩する

次の䟋では、曞評を远跡するためのハッシュマップを定矩しおいたす。ハッシュマップキヌは本の名前であり、倀は読者のレビュヌです。

use std::collections::HashMap;
let mut reviews: HashMap<String, String> = HashMap::new();

reviews.insert(String::from("Ancient Roman History"), String::from("Very accurate."));
reviews.insert(String::from("Cooking with Rhubarb"), String::from("Sweet recipes."));
reviews.insert(String::from("Programming in Rust"), String::from("Great examples."));

このコヌドをさらに詳しく調べおみたしょう。最初の行に、新しいタむプの構文が衚瀺されたす。

use std::collections::HashMap;

このuseコマンドは、Rust暙準ラむブラリの䞀郚HashMapからの定矩をcollectionsプログラムのスコヌプに取り蟌みたす。この構文は、他のプログラミング蚀語がむンポヌトず呌ぶものず䌌おいたす。

HashMap::newメ゜ッドを䜿甚しお空のハッシュマップを䜜成したす。reviews必芁に応じおキヌず倀を远加たたは削陀できるように、倉数を可倉ずしお宣蚀したす。この䟋では、ハッシュマップのキヌず倀の䞡方がStringタむプを䜿甚しおいたす。

let mut reviews: HashMap<String, String> = HashMap::new();

キヌず倀のペアを远加したす

このinsert(<key>, <value>)メ゜ッドを䜿甚しお、ハッシュマップに芁玠を远加したす。コヌドでは、構文は<hash_map_name>.insert()次のずおりです。

reviews.insert(String::from("Ancient Roman History"), String::from("Very accurate."));

キヌ倀を取埗する

ハッシュマップにデヌタを远加した埌、get(<key>)メ゜ッドを䜿甚しおキヌの特定の倀を取埗できたす。

// Look for a specific review
let book: &str = "Programming in Rust";
println!("\nReview for \'{}\': {:?}", book, reviews.get(book));

出力は次のずおりです。

Review for 'Programming in Rust': Some("Great examples.")

ノヌト

出力には、曞評が単なる「すばらしい䟋」ではなく「Some "すばらしい䟋。"」ずしお衚瀺されおいるこずに泚意しおください。getメ゜ッドはOption<&Value>型を返すため、Rustはメ゜ッド呌び出しの結果を「Some」衚蚘でラップしたす。

キヌず倀のペアを削陀したす

この.remove()メ゜ッドを䜿甚しお、ハッシュマップから゚ントリを削陀できたす。get無効なハッシュマップキヌに察しおメ゜ッドを䜿甚するず、getメ゜ッドは「なし」を返したす。

// Remove book review
let obsolete: &str = "Ancient Roman History";
println!("\n'{}\' removed.", obsolete);
reviews.remove(obsolete);

// Confirm book review removed
println!("\nReview for \'{}\': {:?}", obsolete, reviews.get(obsolete));

出力は次のずおりです。

'Ancient Roman History' removed.
Review for 'Ancient Roman History': None

このコヌドを詊しお、このRustPlaygroundでハッシュマップを操䜜できたす。

挔習ハッシュマップを䜿甚しお泚文を远跡する
この挔習では、ハッシュマップを䜿甚するように自動車工堎のプログラムを倉曎したす。

ハッシュマップキヌず倀のペアを䜿甚しお、車の泚文に関する詳现を远跡し、出力を衚瀺したす。繰り返しになりたすが、あなたの課題は、サンプルコヌドを完成させおコンパむルしお実行するこずです。

この挔習のサンプルコヌドで䜜業するには、次の2぀のオプションがありたす。

  • コヌドをコピヌしお、ロヌカル開発環境で線集したす。
  • 準備されたRustPlaygroundでコヌドを開きたす。

ノヌト

サンプルコヌドで、todo!マクロを探したす。このマクロは、完了するか曎新する必芁があるコヌドを瀺したす。

珟圚のプログラムをロヌドする

最初のステップは、既存のプログラムコヌドを取埗するこずです。

  1. 線集のために既存のプログラムコヌドを開きたす。コヌドは、デヌタ型宣蚀、および定矩のため含みcar_quality、car_factoryおよびmain機胜を。

次のコヌドをコピヌしおロヌカル開発環境で線集する
か、この準備されたRustPlaygroundでコヌドを開きたす。

#[derive(PartialEq, Debug)]
struct Car { color: String, motor: Transmission, roof: bool, age: (Age, u32) }

#[derive(PartialEq, Debug)]
enum Transmission { Manual, SemiAuto, Automatic }

#[derive(PartialEq, Debug)]
enum Age { New, Used }

// Get the car quality by testing the value of the input argument
// - miles (u32)
// Return tuple with car age ("New" or "Used") and mileage
fn car_quality (miles: u32) -> (Age, u32) {

    // Check if car has accumulated miles
    // Return tuple early for Used car
    if miles > 0 {
        return (Age::Used, miles);
    }

    // Return tuple for New car, no need for "return" keyword or semicolon
    (Age::New, miles)
}

// Build "Car" using input arguments
fn car_factory(order: i32, miles: u32) -> Car {
    let colors = ["Blue", "Green", "Red", "Silver"];

    // Prevent panic: Check color index for colors array, reset as needed
    // Valid color = 1, 2, 3, or 4
    // If color > 4, reduce color to valid index
    let mut color = order as usize;
    if color > 4 {        
        // color = 5 --> index 1, 6 --> 2, 7 --> 3, 8 --> 4
        color = color - 4;
    }

    // Add variety to orders for motor type and roof type
    let mut motor = Transmission::Manual;
    let mut roof = true;
    if order % 3 == 0 {          // 3, 6, 9
        motor = Transmission::Automatic;
    } else if order % 2 == 0 {   // 2, 4, 8, 10
        motor = Transmission::SemiAuto;
        roof = false;
    }                            // 1, 5, 7, 11

    // Return requested "Car"
    Car {
        color: String::from(colors[(color-1) as usize]),
        motor: motor,
        roof: roof,
        age: car_quality(miles)
    }
}

fn main() {
    // Initialize counter variable
    let mut order = 1;
    // Declare a car as mutable "Car" struct
    let mut car: Car;

    // Order 6 cars, increment "order" for each request
    // Car order #1: Used, Hard top
    car = car_factory(order, 1000);
    println!("{}: {:?}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);

    // Car order #2: Used, Convertible
    order = order + 1;
    car = car_factory(order, 2000);
    println!("{}: {:?}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);    

    // Car order #3: New, Hard top
    order = order + 1;
    car = car_factory(order, 0);
    println!("{}: {:?}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);

    // Car order #4: New, Convertible
    order = order + 1;
    car = car_factory(order, 0);
    println!("{}: {:?}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);

    // Car order #5: Used, Hard top
    order = order + 1;
    car = car_factory(order, 3000);
    println!("{}: {:?}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);

    // Car order #6: Used, Hard top
    order = order + 1;
    car = car_factory(order, 4000);
    println!("{}: {:?}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);
}

2. プログラムをビルドしたす。次のセクションに進む前に、コヌドがコンパむルされお実行されるこずを確認しおください。

次の出力が衚瀺されたす。

1: Used, Hard top = true, Manual, Blue, 1000 miles
2: Used, Hard top = false, SemiAuto, Green, 2000 miles
3: New, Hard top = true, Automatic, Red, 0 miles
4: New, Hard top = false, SemiAuto, Silver, 0 miles
5: Used, Hard top = true, Manual, Blue, 3000 miles
6: Used, Hard top = true, Automatic, Green, 4000 miles

泚文の詳现を远跡するためのハッシュマップを远加する

珟圚のプログラムは、各車の泚文を凊理し、各泚文が完了した埌に芁玄を印刷したす。car_factory関数を呌び出すたびにCar、泚文の詳现を含む構造䜓が返され、泚文が実行されたす。結果はcar倉数に栌玍されたす。

お気づきかもしれたせんが、このプログラムにはいく぀かの重芁な機胜がありたせん。すべおの泚文を远跡しおいるわけではありたせん。car倉数は、珟圚の泚文の詳现のみを保持しおいたす。関数carの結果で倉数が曎新されるたびcar_factoryに、前の順序の詳现が䞊曞きされたす。

ファむリングシステムのようにすべおの泚文を远跡するために、プログラムを曎新する必芁がありたす。この目的のために、<K、V>ペアでハッシュマップを定矩したす。ハッシュマップキヌは、車の泚文番号に察応したす。ハッシュマップ倀は、Car構造䜓で定矩されおいるそれぞれの泚文の詳现になりたす。

  1. ハッシュマップを定矩するには、main関数の先頭、最初の䞭括匧の盎埌に次のコヌドを远加したす{。
// Initialize a hash map for the car orders
    // - Key: Car order number, i32
    // - Value: Car order details, Car struct
    use std::collections::HashMap;
    let mut orders: HashMap<i32, Car> = HashMap;

2. ordersハッシュマップを䜜成するステヌトメントの構文の問題を修正したす。

ヒント

ハッシュマップを最初から䜜成しおいるので、おそらくこのnew()メ゜ッドを䜿甚するこずをお勧めしたす。

3. プログラムをビルドしたす。次のセクションに進む前に、コヌドがコンパむルされおいるこずを確認しおください。コンパむラからの譊告メッセヌゞは無芖しおかたいたせん。

ハッシュマップに倀を远加する

次のステップは、履行された各自動車泚文をハッシュマップに远加するこずです。

このmain関数では、car_factory車の泚文ごずに関数を呌び出したす。泚文が履行された埌、println!マクロを呌び出しお、car倉数に栌玍されおいる泚文の詳现を衚瀺したす。

// Car order #1: Used, Hard top
    car = car_factory(order, 1000);
    println!("{}: {}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);

    ...

    // Car order #6: Used, Hard top
    order = order + 1;
    car = car_factory(order, 4000);
    println!("{}: {}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);

新しいハッシュマップで機胜するように、これらのコヌドステヌトメントを修正したす。

  • car_factory関数の呌び出しは保持したす。返された各Car構造䜓は、ハッシュマップの<K、V>ペアの䞀郚ずしお栌玍されたす。
  • println!マクロの呌び出しを曎新しお、ハッシュマップに保存されおいる泚文の詳现を衚瀺したす。
  1. main関数で、関数の呌び出しcar_factoryずそれに䌎うprintln!マクロの呌び出しを芋぀けたす。
// Car order #1: Used, Hard top
    car = car_factory(order, 1000);
    println!("{}: {}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);

    ...

    // Car order #6: Used, Hard top
    order = order + 1;
    car = car_factory(order, 4000);
    println!("{}: {}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);

2. すべおの自動車泚文のステヌトメントの完党なセットを次の改蚂されたコヌドに眮き換えたす。

// Car order #1: Used, Hard top
    car = car_factory(order, 1000);
    orders(order, car);
    println!("Car order {}: {:?}", order, orders.get(&order));

    // Car order #2: Used, Convertible
    order = order + 1;
    car = car_factory(order, 2000);
    orders(order, car);
    println!("Car order {}: {:?}", order, orders.get(&order));

    // Car order #3: New, Hard top
    order = order + 1;
    car = car_factory(order, 0);
    orders(order, car);
    println!("Car order {}: {:?}", order, orders.get(&order));

    // Car order #4: New, Convertible
    order = order + 1;
    car = car_factory(order, 0);
    orders(order, car);
    println!("Car order {}: {:?}", order, orders.get(&order));

    // Car order #5: Used, Hard top
    order = order + 1;
    car = car_factory(order, 3000);
    orders(order, car);
    println!("Car order {}: {:?}", order, orders.get(&order));

    // Car order #6: Used, Hard top
    order = order + 1;
    car = car_factory(order, 4000);
    orders(order, car);
    println!("Car order {}: {:?}", order, orders.get(&order));

3. 今すぐプログラムをビルドしようずするず、コンパむル゚ラヌが衚瀺されたす。<K、V>ペアをordersハッシュマップに远加するステヌトメントに構文䞊の問題がありたす。問題がありたすか先に進んで、ハッシュマップに順序を远加する各ステヌトメントの問題を修正しおください。

ヒント

ordersハッシュマップに盎接倀を割り圓おるこずはできたせん。挿入を行うにはメ゜ッドを䜿甚する必芁がありたす。

プログラムを実行する

プログラムが正垞にビルドされるず、次の出力が衚瀺されたす。

Car order 1: Some(Car { color: "Blue", motor: Manual, roof: true, age: ("Used", 1000) })
Car order 2: Some(Car { color: "Green", motor: SemiAuto, roof: false, age: ("Used", 2000) })
Car order 3: Some(Car { color: "Red", motor: Automatic, roof: true, age: ("New", 0) })
Car order 4: Some(Car { color: "Silver", motor: SemiAuto, roof: false, age: ("New", 0) })
Car order 5: Some(Car { color: "Blue", motor: Manual, roof: true, age: ("Used", 3000) })
Car order 6: Some(Car { color: "Green", motor: Automatic, roof: true, age: ("Used", 4000) })

改蚂されたコヌドの出力が異なるこずに泚意しおください。println!マクロディスプレむの内容Car各倀を瀺すこずによっお、構造䜓ず察応するフィヌルド名。

次の挔習では、ルヌプ匏を䜿甚しおコヌドの冗長性を枛らしたす。

for、while、およびloop匏を䜿甚したす


倚くの堎合、プログラムには、その堎で繰り返す必芁のあるコヌドのブロックがありたす。ルヌプ匏を䜿甚しお、繰り返しの実行方法をプログラムに指瀺できたす。電話垳のすべおの゚ントリを印刷するには、ルヌプ匏を䜿甚しお、最初の゚ントリから最埌の゚ントリたで印刷する方法をプログラムに指瀺できたす。

Rustは、プログラムにコヌドのブロックを繰り返させるための3぀のルヌプ匏を提䟛したす。

  • loop手動停止が発生しない限り、繰り返したす。
  • while条件が真のたたで繰り返したす。
  • forコレクション内のすべおの倀に察しお繰り返したす。

この単元では、これらの各ルヌプ匏を芋おいきたす。

ルヌプし続けるだけ

loop匏は、無限ルヌプを䜜成したす。このキヌワヌドを䜿甚するず、匏の本文でアクションを継続的に繰り返すこずができたす。ルヌプを停止させるための盎接アクションを実行するたで、アクションが繰り返されたす。

次の䟋では、「We loopforever」ずいうテキストを出力したす。そしおそれはそれ自䜓で止たりたせん。println!アクションは繰り返し続けたす。

loop {
    println!("We loop forever!");
}

loop匏を䜿甚する堎合、ルヌプを停止する唯䞀の方法は、プログラマヌずしお盎接介入する堎合です。特定のコヌドを远加しおルヌプを停止したり、Ctrl + Cなどのキヌボヌド呜什を入力しおプログラムの実行を停止したりできたす。

loop匏を停止する最も䞀般的な方法は、breakキヌワヌドを䜿甚しおブレヌクポむントを蚭定するこずです。

loop {
    // Keep printing, printing, printing...
    println!("We loop forever!");
    // On the other hand, maybe we should stop!
    break;                            
}

プログラムがbreakキヌワヌドを怜出するず、loop匏の本䜓でアクションの実行を停止し、次のコヌドステヌトメントに進みたす。

breakキヌワヌドは、特別な機胜を明らかにするloop衚珟を。breakキヌワヌドを䜿甚するず、匏本䜓でのアクションの繰り返しを停止するこずも、ブレヌクポむントで倀を返すこずもできたす。

次の䟋はbreak、loop匏でキヌワヌドを䜿甚しお倀も返す方法を瀺しおいたす。

let mut counter = 1;
// stop_loop is set when loop stops
let stop_loop = loop {
    counter *= 2;
    if counter > 100 {
        // Stop loop, return counter value
        break counter;
    }
};
// Loop should break when counter = 128
println!("Break the loop at counter = {}.", stop_loop);

出力は次のずおりです。

Break the loop at counter = 128.

私たちのloop衚珟の本䜓は、これらの連続したアクションを実行したす。

  1. stop_loop倉数を宣蚀したす。
  2. 倉数倀をloop匏の結果にバむンドするようにプログラムに指瀺したす。
  3. ルヌプを開始したす。loop匏の本䜓でアクションを実行したす
    ルヌプ本䜓
    1. counter倀を珟圚の倀の2倍にむンクリメントしたす。
    2. counter倀を確認しおください。
    3. もしcounter倀が100以䞊です。

ルヌプから抜け出し、counter倀を返したす。

4. もしcounter倀が100以䞊ではありたせん。

ルヌプ本䜓でアクションを繰り返したす。

5. stop_loop倀を匏のcounter結果である倀に蚭定したすloop。

loop匏本䜓は、耇数のブレヌクポむントを持぀こずができたす。匏に耇数のブレヌクポむントがある堎合、すべおのブレヌクポむントは同じタむプの倀を返す必芁がありたす。すべおの倀は、敎数型、文字列型、ブヌル型などである必芁がありたす。ブレヌクポむントが明瀺的に倀を返さない堎合、プログラムは匏の結果を空のタプルずしお解釈したす()。

しばらくルヌプする

whileルヌプは、条件匏を䜿甚しおいたす。条件匏が真である限り、ルヌプが繰り返されたす。このキヌワヌドを䜿甚するず、条件匏がfalseになるたで、匏本䜓のアクションを実行できたす。

whileルヌプは、ブヌル条件匏を評䟡するこずから始たりたす。条件匏がず評䟡されるtrueず、本䜓のアクションが実行されたす。アクションが完了するず、制埡は条件匏に戻りたす。条件匏がず評䟡されるfalseず、while匏は停止したす。

次の䟋では、「しばらくルヌプしたす...」ずいうテキストを出力したす。ルヌプを繰り返すたびに、「カりントが5未満である」ずいう条件がテストされたす。条件が真のたたである間、匏本䜓のアクションが実行されたす。条件が真でなくなった埌、whileルヌプは停止し、プログラムは次のコヌドステヌトメントに進みたす。

while counter < 5 {
    println!("We loop a while...");
    counter = counter + 1;
}

これらの倀のルヌプ

forルヌプは、項目のコレクションを凊理するためにむテレヌタを䜿甚しおいたす。ルヌプは、コレクション内の各アむテムの匏本䜓のアクションを繰り返したす。このタむプのルヌプの繰り返しは、反埩ず呌ばれたす。すべおの反埩が完了するず、ルヌプは停止したす。

Rustでは、配列、ベクトル、ハッシュマップなど、任意のコレクションタむプを反埩凊理できたす。Rustはむテレヌタを䜿甚しお、コレクション内の各アむテムを最初から最埌たで移動したす。

forルヌプはむテレヌタずしお䞀時倉数を䜿甚しおいたす。倉数はルヌプ匏の開始時に暗黙的に宣蚀され、珟圚の倀は反埩ごずに蚭定されたす。

次のコヌドでは、コレクションはbig_birds配列であり、むテレヌタヌの名前はbirdです。

let big_birds = ["ostrich", "peacock", "stork"];
for bird in big_birds

iter()メ゜ッドを䜿甚しお、コレクション内のアむテムにアクセスしたす。for匏は結果にむテレヌタの珟圚の倀をバむンドするiter()方法。匏本䜓では、むテレヌタ倀を操䜜できたす。

let big_birds = ["ostrich", "peacock", "stork"];
for bird in big_birds.iter() {
    println!("The {} is a big bird.", bird);
}

出力は次のずおりです。

The ostrich is a big bird.
The peacock is a big bird.
The stork is a big bird.

むテレヌタを䜜成するもう1぀の簡単な方法は、範囲衚蚘を䜿甚するこずですa..b。むテレヌタはa倀から始たりb、1ステップず぀続きたすが、倀を䜿甚したせんb。

for number in 0..5 {
    println!("{}", number * 2);
}

このコヌドは、0、1、2、3、および4の数倀をnumber繰り返し凊理したす。ルヌプの繰り返しごずに、倀を倉数にバむンドしたす。

出力は次のずおりです。

0
2
4
6
8

このコヌドを実行しお、このRustPlaygroundでルヌプを探玢できたす。

挔習ルヌプを䜿甚しおデヌタを反埩凊理する


この挔習では、自動車工堎のプログラムを倉曎しお、ルヌプを䜿甚しお自動車の泚文を反埩凊理したす。

main関数を曎新しお、泚文の完党なセットを凊理するためのルヌプ匏を远加したす。ルヌプ構造は、コヌドの冗長性を枛らすのに圹立ちたす。コヌドを簡玠化するこずで、泚文量を簡単に増やすこずができたす。

このcar_factory関数では、範囲倖の倀での実行時のパニックを回避するために、別のルヌプを远加したす。

課題は、サンプルコヌドを完成させお、コンパむルしお実行するこずです。

この挔習のサンプルコヌドで䜜業するには、次の2぀のオプションがありたす。

  • コヌドをコピヌしお、ロヌカル開発環境で線集したす。
  • 準備されたRustPlaygroundでコヌドを開きたす。

ノヌト

サンプルコヌドで、todo!マクロを探したす。このマクロは、完了するか曎新する必芁があるコヌドを瀺したす。

プログラムをロヌドする

前回の挔習でプログラムコヌドを閉じた堎合は、この準備されたRustPlaygroundでコヌドを再床開くこずができたす。

必ずプログラムを再構築し、コンパむラ゚ラヌなしで実行されるこずを確認しおください。

ルヌプ匏でアクションを繰り返す

より倚くの泚文をサポヌトするには、プログラムを曎新する必芁がありたす。珟圚のコヌド構造では、冗長ステヌトメントを䜿甚しお6぀の泚文をサポヌトしおいたす。冗長性は扱いにくく、維持するのが困難です。

ルヌプ匏を䜿甚しおアクションを繰り返し、各泚文を䜜成するこずで、構造を単玔化できたす。簡略化されたコヌドを䜿甚するず、倚数の泚文をすばやく䜜成できたす。

  1. ではmain機胜、削陀次の文を。このコヌドブロックは、order倉数を定矩および蚭定し、自動車の泚文のcar_factory関数ずprintln!マクロを呌び出し、各泚文をordersハッシュマップに挿入したす。
// Order 6 cars
    // - Increment "order" after each request
    // - Add each order <K, V> pair to "orders" hash map
    // - Call println! to show order details from the hash map

    // Initialize order variable
    let mut order = 1;

    // Car order #1: Used, Hard top
    car = car_factory(order, 1000);
    orders.insert(order, car);
    println!("Car order {}: {:?}", order, orders.get(&order));

    ...

    // Car order #6: Used, Hard top
    order = order + 1;
    car = car_factory(order, 4000);
    orders.insert(order, car);
    println!("Car order {}: {:?}", order, orders.get(&order));

2. 削陀されたステヌトメントを次のコヌドブロックに眮き換えたす。

// Start with zero miles
    let mut miles = 0;

    todo!("Add a loop expression to fulfill orders for 6 cars, initialize `order` variable to 1") {

        // Call car_factory to fulfill order
        // Add order <K, V> pair to "orders" hash map
        // Call println! to show order details from the hash map        
        car = car_factory(order, miles);
        orders.insert(order, car);
        println!("Car order {}: {:?}", order, orders.get(&order));

        // Reset miles for order variety
        if miles == 2100 {
            miles = 0;
        } else {
            miles = miles + 700;
        }
    }

3. アクションを繰り返すルヌプ匏を远加しお、6台の車の泚文を䜜成したす。order1に初期化された倉数が必芁です。

4. プログラムをビルドしたす。コヌドが゚ラヌなしでコンパむルされるこずを確認しおください。

次の䟋のような出力が衚瀺されたす。

Car order 1: Some(Car { color: "Blue", motor: Manual, roof: true, age: ("New", 0) })
Car order 2: Some(Car { color: "Green", motor: SemiAuto, roof: false, age: ("Used", 700) })
Car order 3: Some(Car { color: "Red", motor: Automatic, roof: true, age: ("Used", 1400) })
Car order 4: Some(Car { color: "Silver", motor: SemiAuto, roof: false, age: ("Used", 2100) })
Car order 5: Some(Car { color: "Blue", motor: Manual, roof: true, age: ("New", 0) })
Car order 6: Some(Car { color: "Green", motor: Automatic, roof: true, age: ("Used", 700) })

車の泚文を11に増やす

 ãƒ—ログラムは珟圚、ルヌプを䜿甚しお6台の車の泚文を凊理しおいたす。6台以䞊泚文するずどうなりたすか

  1. main関数のルヌプ匏を曎新しお、11台の車を泚文したす。
    todo!("Update the loop expression to create 11 cars");

2. プログラムを再構築したす。実行時に、プログラムはパニックになりたす

Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 1.26s
    Running `target/debug/playground`
thread 'main' panicked at 'index out of bounds: the len is 4 but the index is 4', src/main.rs:34:29

この問題を解決する方法を芋おみたしょう。

ルヌプ匏で実行時のパニックを防ぐ

このcar_factory関数では、if / else匏を䜿甚colorしお、colors配列のむンデックスの倀を確認したす。

// Prevent panic: Check color index for colors array, reset as needed
    // Valid color = 1, 2, 3, or 4
    // If color > 4, reduce color to valid index
    let mut color = order as usize;
    if color > 4 {        
        // color = 5 --> index 1, 6 --> 2, 7 --> 3, 8 --> 4
        color = color - 4;
    }

colors配列には4぀の芁玠を持ち、か぀有効なcolor堎合は、むンデックスの範囲は0〜3の条件匏をチェックしおいるcolor私たちはをチェックしたせんむンデックスが4よりも倧きい堎合color、その埌の関数で4に等しいむンデックスぞのずきに我々のむンデックスを車の色を割り圓おる配列では、むンデックス倀から1を枛算したすcolor - 1。color倀4はcolors[3]、配列ず同様に凊理されたす。

珟圚のif / else匏は、8台以䞋の車を泚文するずきの実行時のパニックを防ぐためにうたく機胜したす。しかし、11台の車を泚文するず、プログラムは9番目の泚文でパニックになりたす。より堅牢になるように匏を調敎する必芁がありたす。この改善を行うために、別のルヌプ匏を䜿甚したす。

  1. ではcar_factory機胜、ルヌプ匏であれば/他の条件文を亀換しおください。colorむンデックス倀が4より倧きい堎合に実行時のパニックを防ぐために、次の擬䌌コヌドステヌトメントを修正しおください。
// Prevent panic: Check color index, reset as needed
    // If color = 1, 2, 3, or 4 - no change needed
    // If color > 4, reduce to color to a valid index
    let mut color = order as usize;
    todo!("Replace `if/else` condition with a loop to prevent run-time panic for color > 4");

ヒント

この堎合、if / else条件からルヌプ匏ぞの倉曎は実際には非垞に簡単です。

2. プログラムをビルドしたす。コヌドが゚ラヌなしでコンパむルされるこずを確認しおください。

次の出力が衚瀺されたす。

Car order 1: Some(Car { color: "Blue", motor: Manual, roof: true, age: ("New", 0) })
Car order 2: Some(Car { color: "Green", motor: SemiAuto, roof: false, age: ("Used", 700) })
Car order 3: Some(Car { color: "Red", motor: Automatic, roof: true, age: ("Used", 1400) })
Car order 4: Some(Car { color: "Silver", motor: SemiAuto, roof: false, age: ("Used", 2100) })
Car order 5: Some(Car { color: "Blue", motor: Manual, roof: true, age: ("New", 0) })
Car order 6: Some(Car { color: "Green", motor: Automatic, roof: true, age: ("Used", 700) })
Car order 7: Some(Car { color: "Red", motor: Manual, roof: true, age: ("Used", 1400) })
Car order 8: Some(Car { color: "Silver", motor: SemiAuto, roof: false, age: ("Used", 2100) })
Car order 9: Some(Car { color: "Blue", motor: Automatic, roof: true, age: ("New", 0) })
Car order 10: Some(Car { color: "Green", motor: SemiAuto, roof: false, age: ("Used", 700) })
Car order 11: Some(Car { color: "Red", motor: Manual, roof: true, age: ("Used", 1400) })

抂芁

このモゞュヌルでは、Rustで䜿甚できるさたざたなルヌプ匏を調べ、ハッシュマップの操䜜方法を発芋したした。デヌタは、キヌず倀のペアずしおハッシュマップに保存されたす。ハッシュマップは拡匵可胜です。

loop手動でプロセスを停止するたでの匏は、アクションを繰り返したす。while匏をルヌプしお、条件が真である限りアクションを繰り返すこずができたす。このfor匏は、デヌタ収集を反埩凊理するために䜿甚されたす。

この挔習では、自動車プログラムを拡匵しお、繰り返されるアクションをルヌプし、すべおの泚文を凊理したした。泚文を远跡するためにハッシュマップを実装したした。

このラヌニングパスの次のモゞュヌルでは、Rustコヌドで゚ラヌず障害がどのように凊理されるかに぀いお詳しく説明したす。

 ãƒªãƒ³ã‚¯: https://docs.microsoft.com/en-us/learn/modules/rust-loop-expressions/

#rust #Beginners 

anita maity

anita maity

1619013192

Create a Personal Portfolio Website Using HTML CSS and JavaScript

Demo Click Here: https://cutt.ly/2vFKuxe

#portfolio website html css #personal website html css #personal portfolio website #how to create a complete peronal portfolio website #responsive portfolio website html css #responsive personal portfolio website html css