Barry  Powell

Barry Powell

1626890820

Bluehost Wordpress Install (In 6 Easy Steps) How To Install WordPress On Bluehost 2020

Bluehost Wordpress Install - How To Install WordPress On Bluehost 2020

Timestamps 👇

00:00 Intro
00:16 Get Your Hosting Discount
00:34 Select Your Hosting Package
01:01 Pick Your Domain Name
02:03 Additional Discount
03:16 Log Into The Bluehost Dashboard
04:21 Go To “My Sites”
04:31 Click “Log Into WordPress”
05:07 Confirm Your Email Address
06:08 Go To My Sites and Click “Manage Site”
06:24 Click “Launch Your Site”
06:35 For The People Who Already Have Bluehost

Step 1 - Go to Your Bluehost Dashboard

Before this step, make sure you’re fully set-up with Bluehost and have a WordPress account. Considering you’re reading a guide on how to install WordPress on Bluehost, you most likely have already done that. Nonetheless, make sure you have a Bluehost plan selected and a WordPress account to begin with.

Once you’ve done that, go to your Bluehost dashboard. At this point, you have everything needed, you just have to install WordPress on Bluehost. On your dashboard, you should see a variety of tabs such as home, sites, marketplace, email, domains, and advanced. At this point, don’t worry about all of them for the time being. Just make sure you’re on the Bluehost dashboard.

Step 2 - Go to the Left Sidebar and Click on “my sites”

Now that you’re on your Bluehost dashboard. Take a look at the left sidebar, and look for my sites. It should be the 2nd one from the top, and not too tricky to find. Once discovered, click on it. This tab is where you’ll control all of your sites you have connected to Bluehost, and will use to add new sites.

Be familiar with this tab if you want to add more sites, remove a site, and so on. Plus, it’s where you’ll go to connect WordPress on Bluehost. Bluehost has a straightforward set-up system, which makes them one of the best options to choose from. Nonetheless, click on my sites, and you can move on to step three.

Step 3 - Click on the Blue “create site” Button

Once you’re on the my sites tab, next, you’ll click on create site. Unless you already have a website connected to Bluehost, you shouldn’t see any websites down below. If you have a bunch of websites on there, you most likely wouldn’t be using this guide anyway.

Nonetheless, click on create site, and you’ll be ready for the next step. Keep this in mind for when you want to add future sites. No matter what the case might be, this is a simple tool for installing WordPress on Bluehost. Let’s move on.

Step 4 - When it Asks You, “How would you like to build your website?” Click on the blue “use WordPress” button

Once you click on create site, it’ll ask you how you’ll like to build your website. Building your website comes in a variety of options, but make sure you hit the use WordPress button. That way, you’ll be able to easily install WordPress on Bluehost.

Bluehost tries to make WordPress’s installation process remarkably simple and is why the entire method only takes a matter of a few buttons. Once you use the WordPress button, you only have a few more steps left in the whole process. Let’s continue forward!

Step 5 - Add a Title to Your Website and Click Next

Almost at the finish point, add a title to your website. Think of the title as what you want to represent your website. If you’re not sure of a title to utilize, don’t worry too much about it. Take the needed time to think of one and move forward from there. Nonetheless, once you know of a title to your website, click next.

Now that you added the title to your website, it shouldn’t be much longer from that point moving forward. At this point, the installation of WordPress is almost entirely complete. It just needs a final step to complete the process. Let’s look at the last step!

(Final step) Step 6 - Select your Website from the drop-down menu and click Next

Congratulations, you’re on the last step! At this point, go to the drop-down menu and select your website. Unless you have numerous websites connected to Bluehost, it should only pop-up with one site. Simple enough, right?

Once you see your website, click on it, and click next. Once the process completes, there shouldn’t be any other future needs to properly install WordPress on Bluehost. You shouldn’t have any issues related to this since Bluehost makes it such a straightforward process with installing process.

WordPress is Now Installed!

Note: To keep these video tutorials free, I make a small commission every time you purchase through the links in the description.

#Bluehost #BluehostWordPressInstall #BluehostWordPress

#wordpress

What is GEEK

Buddha Community

Bluehost Wordpress Install (In 6 Easy Steps) How To Install WordPress On Bluehost 2020
John  Smith

John Smith

1657107416

Find the Best Restaurant Mobile App Development Company in Abu Dhbai

The era of mobile app development has completely changed the scenario for businesses in regions like Abu Dhabi. Restaurants and food delivery businesses are experiencing huge benefits via smart business applications. The invention and development of the food ordering app have helped all-scale businesses reach new customers and boost sales and profit. 

As a result, many business owners are searching for the best restaurant mobile app development company in Abu Dhabi. If you are also searching for the same, this article is helpful for you. It will let you know the step-by-step process to hire the right team of restaurant mobile app developers. 

Step-by-Step Process to Find the Best Restaurant App Development Company

Searching for the top mobile app development company in Abu Dhabi? Don't know the best way to search for professionals? Don't panic! Here is the step-by-step process to hire the best professionals. 

#Step 1 – Know the Company's Culture

Knowing the organization's culture is very crucial before finalizing a food ordering app development company in Abu Dhabi. An organization's personality is shaped by its common beliefs, goals, practices, or company culture. So, digging into the company culture reveals the core beliefs of the organization, its objectives, and its development team. 

Now, you might be wondering, how will you identify the company's culture? Well, you can take reference from the following sources – 

  • Social media posts 
  • App development process
  • About us Page
  • Client testimonials

#Step 2 - Refer to Clients' Reviews

Another best way to choose the On-demand app development firm for your restaurant business is to refer to the clients' reviews. Reviews are frequently available on the organization's website with a tag of "Reviews" or "Testimonials." It's important to read the reviews as they will help you determine how happy customers are with the company's app development process. 

You can also assess a company's abilities through reviews and customer testimonials. They can let you know if the mobile app developers create a valuable app or not. 

#Step 3 – Analyze the App Development Process

Regardless of the company's size or scope, adhering to the restaurant delivery app development process will ensure the success of your business application. Knowing the processes an app developer follows in designing and producing a top-notch app will help you know the working process. Organizations follow different app development approaches, so getting well-versed in the process is essential before finalizing any mobile app development company. 

#Step 4 – Consider Previous Experience

Besides considering other factors, considering the previous experience of the developers is a must. You can obtain a broad sense of the developer's capacity to assist you in creating a unique mobile application for a restaurant business.

You can also find out if the developers' have contributed to the creation of other successful applications or not. It will help you know the working capacity of a particular developer or organization. Prior experience is essential to evaluating their work. For instance, whether they haven't previously produced an app similar to yours or not. 

#Step 5 – Check for Their Technical Support

As you expect a working and successful restaurant mobile app for your business, checking on this factor is a must. A well-established organization is nothing without a good technical support team. So, ensure whatever restaurant mobile app development company you choose they must be well-equipped with a team of dedicated developers, designers, and testers. 

Strong tech support from your mobile app developers will help you identify new bugs and fix them bugs on time. All this will ensure the application's success. 

#Step 6 – Analyze Design Standards

Besides focusing on an organization's development, testing, and technical support, you should check the design standards. An appealing design is crucial in attracting new users and keeping the existing ones stick to your services. So, spend some time analyzing the design standards of an organization. Now, you might be wondering, how will you do it? Simple! By looking at the organization's portfolio. 

Whether hiring an iPhone app development company or any other, these steps apply to all. So, don't miss these steps. 

#Step 7 – Know Their Location

Finally, the last yet very crucial factor that will not only help you finalize the right person for your restaurant mobile app development but will also decide the mobile app development cost. So, you have to choose the location of the developers wisely, as it is a crucial factor in defining the cost. 

Summing Up!!!

Restaurant mobile applications have taken the food industry to heights none have ever considered. As a result, the demand for restaurant mobile app development companies has risen greatly, which is why businesses find it difficult to finalize the right person. But, we hope that after referring to this article, it will now be easier to hire dedicated developers under the desired budget. So, begin the hiring process now and get a well-craft food ordering app in hand. 

Brain  Crist

Brain Crist

1594753020

Citrix Bugs Allow Unauthenticated Code Injection, Data Theft

Multiple vulnerabilities in the Citrix Application Delivery Controller (ADC) and Gateway would allow code injection, information disclosure and denial of service, the networking vendor announced Tuesday. Four of the bugs are exploitable by an unauthenticated, remote attacker.

The Citrix products (formerly known as NetScaler ADC and Gateway) are used for application-aware traffic management and secure remote access, respectively, and are installed in at least 80,000 companies in 158 countries, according to a December assessment from Positive Technologies.

Other flaws announced Tuesday also affect Citrix SD-WAN WANOP appliances, models 4000-WO, 4100-WO, 5000-WO and 5100-WO.

Attacks on the management interface of the products could result in system compromise by an unauthenticated user on the management network; or system compromise through cross-site scripting (XSS). Attackers could also create a download link for the device which, if downloaded and then executed by an unauthenticated user on the management network, could result in the compromise of a local computer.

“Customers who have configured their systems in accordance with Citrix recommendations [i.e., to have this interface separated from the network and protected by a firewall] have significantly reduced their risk from attacks to the management interface,” according to the vendor.

Threat actors could also mount attacks on Virtual IPs (VIPs). VIPs, among other things, are used to provide users with a unique IP address for communicating with network resources for applications that do not allow multiple connections or users from the same IP address.

The VIP attacks include denial of service against either the Gateway or Authentication virtual servers by an unauthenticated user; or remote port scanning of the internal network by an authenticated Citrix Gateway user.

“Attackers can only discern whether a TLS connection is possible with the port and cannot communicate further with the end devices,” according to the critical Citrix advisory. “Customers who have not enabled either the Gateway or Authentication virtual servers are not at risk from attacks that are applicable to those servers. Other virtual servers e.g. load balancing and content switching virtual servers are not affected by these issues.”

A final vulnerability has been found in Citrix Gateway Plug-in for Linux that would allow a local logged-on user of a Linux system with that plug-in installed to elevate their privileges to an administrator account on that computer, the company said.

#vulnerabilities #adc #citrix #code injection #critical advisory #cve-2020-8187 #cve-2020-8190 #cve-2020-8191 #cve-2020-8193 #cve-2020-8194 #cve-2020-8195 #cve-2020-8196 #cve-2020-8197 #cve-2020-8198 #cve-2020-8199 #denial of service #gateway #information disclosure #patches #security advisory #security bugs

Dylan  Iqbal

Dylan Iqbal

1561523460

Matplotlib Cheat Sheet: Plotting in Python

This Matplotlib cheat sheet introduces you to the basics that you need to plot your data with Python and includes code samples.

Data visualization and storytelling with your data are essential skills that every data scientist needs to communicate insights gained from analyses effectively to any audience out there. 

For most beginners, the first package that they use to get in touch with data visualization and storytelling is, naturally, Matplotlib: it is a Python 2D plotting library that enables users to make publication-quality figures. But, what might be even more convincing is the fact that other packages, such as Pandas, intend to build more plotting integration with Matplotlib as time goes on.

However, what might slow down beginners is the fact that this package is pretty extensive. There is so much that you can do with it and it might be hard to still keep a structure when you're learning how to work with Matplotlib.   

DataCamp has created a Matplotlib cheat sheet for those who might already know how to use the package to their advantage to make beautiful plots in Python, but that still want to keep a one-page reference handy. Of course, for those who don't know how to work with Matplotlib, this might be the extra push be convinced and to finally get started with data visualization in Python. 

You'll see that this cheat sheet presents you with the six basic steps that you can go through to make beautiful plots. 

Check out the infographic by clicking on the button below:

Python Matplotlib cheat sheet

With this handy reference, you'll familiarize yourself in no time with the basics of Matplotlib: you'll learn how you can prepare your data, create a new plot, use some basic plotting routines to your advantage, add customizations to your plots, and save, show and close the plots that you make.

What might have looked difficult before will definitely be more clear once you start using this cheat sheet! Use it in combination with the Matplotlib Gallery, the documentation.

Matplotlib 

Matplotlib is a Python 2D plotting library which produces publication-quality figures in a variety of hardcopy formats and interactive environments across platforms.

Prepare the Data 

1D Data 

>>> import numpy as np
>>> x = np.linspace(0, 10, 100)
>>> y = np.cos(x)
>>> z = np.sin(x)

2D Data or Images 

>>> data = 2 * np.random.random((10, 10))
>>> data2 = 3 * np.random.random((10, 10))
>>> Y, X = np.mgrid[-3:3:100j, -3:3:100j]
>>> U = 1 X** 2 + Y
>>> V = 1 + X Y**2
>>> from matplotlib.cbook import get_sample_data
>>> img = np.load(get_sample_data('axes_grid/bivariate_normal.npy'))

Create Plot

>>> import matplotlib.pyplot as plt

Figure 

>>> fig = plt.figure()
>>> fig2 = plt.figure(figsize=plt.figaspect(2.0))

Axes 

>>> fig.add_axes()
>>> ax1 = fig.add_subplot(221) #row-col-num
>>> ax3 = fig.add_subplot(212)
>>> fig3, axes = plt.subplots(nrows=2,ncols=2)
>>> fig4, axes2 = plt.subplots(ncols=3)

Save Plot 

>>> plt.savefig('foo.png') #Save figures
>>> plt.savefig('foo.png',  transparent=True) #Save transparent figures

Show Plot

>>> plt.show()

Plotting Routines 

1D Data 

>>> fig, ax = plt.subplots()
>>> lines = ax.plot(x,y) #Draw points with lines or markers connecting them
>>> ax.scatter(x,y) #Draw unconnected points, scaled or colored
>>> axes[0,0].bar([1,2,3],[3,4,5]) #Plot vertical rectangles (constant width)
>>> axes[1,0].barh([0.5,1,2.5],[0,1,2]) #Plot horiontal rectangles (constant height)
>>> axes[1,1].axhline(0.45) #Draw a horizontal line across axes
>>> axes[0,1].axvline(0.65) #Draw a vertical line across axes
>>> ax.fill(x,y,color='blue') #Draw filled polygons
>>> ax.fill_between(x,y,color='yellow') #Fill between y values and 0

2D Data 

>>> fig, ax = plt.subplots()
>>> im = ax.imshow(img, #Colormapped or RGB arrays
      cmap= 'gist_earth', 
      interpolation= 'nearest',
      vmin=-2,
      vmax=2)
>>> axes2[0].pcolor(data2) #Pseudocolor plot of 2D array
>>> axes2[0].pcolormesh(data) #Pseudocolor plot of 2D array
>>> CS = plt.contour(Y,X,U) #Plot contours
>>> axes2[2].contourf(data1) #Plot filled contours
>>> axes2[2]= ax.clabel(CS) #Label a contour plot

Vector Fields 

>>> axes[0,1].arrow(0,0,0.5,0.5) #Add an arrow to the axes
>>> axes[1,1].quiver(y,z) #Plot a 2D field of arrows
>>> axes[0,1].streamplot(X,Y,U,V) #Plot a 2D field of arrows

Data Distributions 

>>> ax1.hist(y) #Plot a histogram
>>> ax3.boxplot(y) #Make a box and whisker plot
>>> ax3.violinplot(z)  #Make a violin plot

Plot Anatomy & Workflow 

Plot Anatomy 

 y-axis      

                           x-axis 

Workflow 

The basic steps to creating plots with matplotlib are:

1 Prepare Data
2 Create Plot
3 Plot
4 Customized Plot
5 Save Plot
6 Show Plot

>>> import matplotlib.pyplot as plt
>>> x = [1,2,3,4]  #Step 1
>>> y = [10,20,25,30] 
>>> fig = plt.figure() #Step 2
>>> ax = fig.add_subplot(111) #Step 3
>>> ax.plot(x, y, color= 'lightblue', linewidth=3)  #Step 3, 4
>>> ax.scatter([2,4,6],
          [5,15,25],
          color= 'darkgreen',
          marker= '^' )
>>> ax.set_xlim(1, 6.5)
>>> plt.savefig('foo.png' ) #Step 5
>>> plt.show() #Step 6

Close and Clear 

>>> plt.cla()  #Clear an axis
>>> plt.clf(). #Clear the entire figure
>>> plt.close(). #Close a window

Plotting Customize Plot 

Colors, Color Bars & Color Maps 

>>> plt.plot(x, x, x, x**2, x, x** 3)
>>> ax.plot(x, y, alpha = 0.4)
>>> ax.plot(x, y, c= 'k')
>>> fig.colorbar(im, orientation= 'horizontal')
>>> im = ax.imshow(img,
            cmap= 'seismic' )

Markers 

>>> fig, ax = plt.subplots()
>>> ax.scatter(x,y,marker= ".")
>>> ax.plot(x,y,marker= "o")

Linestyles 

>>> plt.plot(x,y,linewidth=4.0)
>>> plt.plot(x,y,ls= 'solid') 
>>> plt.plot(x,y,ls= '--') 
>>> plt.plot(x,y,'--' ,x**2,y**2,'-.' ) 
>>> plt.setp(lines,color= 'r',linewidth=4.0)

Text & Annotations 

>>> ax.text(1,
           -2.1, 
           'Example Graph', 
            style= 'italic' )
>>> ax.annotate("Sine", 
xy=(8, 0),
xycoords= 'data', 
xytext=(10.5, 0),
textcoords= 'data', 
arrowprops=dict(arrowstyle= "->", 
connectionstyle="arc3"),)

Mathtext 

>>> plt.title(r '$sigma_i=15$', fontsize=20)

Limits, Legends and Layouts 

Limits & Autoscaling 

>>> ax.margins(x=0.0,y=0.1) #Add padding to a plot
>>> ax.axis('equal')  #Set the aspect ratio of the plot to 1
>>> ax.set(xlim=[0,10.5],ylim=[-1.5,1.5])  #Set limits for x-and y-axis
>>> ax.set_xlim(0,10.5) #Set limits for x-axis

Legends 

>>> ax.set(title= 'An Example Axes',  #Set a title and x-and y-axis labels
            ylabel= 'Y-Axis', 
            xlabel= 'X-Axis')
>>> ax.legend(loc= 'best')  #No overlapping plot elements

Ticks 

>>> ax.xaxis.set(ticks=range(1,5),  #Manually set x-ticks
             ticklabels=[3,100, 12,"foo" ])
>>> ax.tick_params(axis= 'y', #Make y-ticks longer and go in and out
             direction= 'inout', 
              length=10)

Subplot Spacing 

>>> fig3.subplots_adjust(wspace=0.5,   #Adjust the spacing between subplots
             hspace=0.3,
             left=0.125,
             right=0.9,
             top=0.9,
             bottom=0.1)
>>> fig.tight_layout() #Fit subplot(s) in to the figure area

Axis Spines 

>>> ax1.spines[ 'top'].set_visible(False) #Make the top axis line for a plot invisible
>>> ax1.spines['bottom' ].set_position(( 'outward',10))  #Move the bottom axis line outward

Have this Cheat Sheet at your fingertips

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

#matplotlib #cheatsheet #python

Barry  Powell

Barry Powell

1626890820

Bluehost Wordpress Install (In 6 Easy Steps) How To Install WordPress On Bluehost 2020

Bluehost Wordpress Install - How To Install WordPress On Bluehost 2020

Timestamps 👇

00:00 Intro
00:16 Get Your Hosting Discount
00:34 Select Your Hosting Package
01:01 Pick Your Domain Name
02:03 Additional Discount
03:16 Log Into The Bluehost Dashboard
04:21 Go To “My Sites”
04:31 Click “Log Into WordPress”
05:07 Confirm Your Email Address
06:08 Go To My Sites and Click “Manage Site”
06:24 Click “Launch Your Site”
06:35 For The People Who Already Have Bluehost

Step 1 - Go to Your Bluehost Dashboard

Before this step, make sure you’re fully set-up with Bluehost and have a WordPress account. Considering you’re reading a guide on how to install WordPress on Bluehost, you most likely have already done that. Nonetheless, make sure you have a Bluehost plan selected and a WordPress account to begin with.

Once you’ve done that, go to your Bluehost dashboard. At this point, you have everything needed, you just have to install WordPress on Bluehost. On your dashboard, you should see a variety of tabs such as home, sites, marketplace, email, domains, and advanced. At this point, don’t worry about all of them for the time being. Just make sure you’re on the Bluehost dashboard.

Step 2 - Go to the Left Sidebar and Click on “my sites”

Now that you’re on your Bluehost dashboard. Take a look at the left sidebar, and look for my sites. It should be the 2nd one from the top, and not too tricky to find. Once discovered, click on it. This tab is where you’ll control all of your sites you have connected to Bluehost, and will use to add new sites.

Be familiar with this tab if you want to add more sites, remove a site, and so on. Plus, it’s where you’ll go to connect WordPress on Bluehost. Bluehost has a straightforward set-up system, which makes them one of the best options to choose from. Nonetheless, click on my sites, and you can move on to step three.

Step 3 - Click on the Blue “create site” Button

Once you’re on the my sites tab, next, you’ll click on create site. Unless you already have a website connected to Bluehost, you shouldn’t see any websites down below. If you have a bunch of websites on there, you most likely wouldn’t be using this guide anyway.

Nonetheless, click on create site, and you’ll be ready for the next step. Keep this in mind for when you want to add future sites. No matter what the case might be, this is a simple tool for installing WordPress on Bluehost. Let’s move on.

Step 4 - When it Asks You, “How would you like to build your website?” Click on the blue “use WordPress” button

Once you click on create site, it’ll ask you how you’ll like to build your website. Building your website comes in a variety of options, but make sure you hit the use WordPress button. That way, you’ll be able to easily install WordPress on Bluehost.

Bluehost tries to make WordPress’s installation process remarkably simple and is why the entire method only takes a matter of a few buttons. Once you use the WordPress button, you only have a few more steps left in the whole process. Let’s continue forward!

Step 5 - Add a Title to Your Website and Click Next

Almost at the finish point, add a title to your website. Think of the title as what you want to represent your website. If you’re not sure of a title to utilize, don’t worry too much about it. Take the needed time to think of one and move forward from there. Nonetheless, once you know of a title to your website, click next.

Now that you added the title to your website, it shouldn’t be much longer from that point moving forward. At this point, the installation of WordPress is almost entirely complete. It just needs a final step to complete the process. Let’s look at the last step!

(Final step) Step 6 - Select your Website from the drop-down menu and click Next

Congratulations, you’re on the last step! At this point, go to the drop-down menu and select your website. Unless you have numerous websites connected to Bluehost, it should only pop-up with one site. Simple enough, right?

Once you see your website, click on it, and click next. Once the process completes, there shouldn’t be any other future needs to properly install WordPress on Bluehost. You shouldn’t have any issues related to this since Bluehost makes it such a straightforward process with installing process.

WordPress is Now Installed!

Note: To keep these video tutorials free, I make a small commission every time you purchase through the links in the description.

#Bluehost #BluehostWordPressInstall #BluehostWordPress

#wordpress

ルヌプを䜿甚しお、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