Go Series Tutorial--6. Functions (function)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. This is our [Golang Series Tutorial] (/SUBJECT/2) 6th chapter, learn the knowledge of Golang function. # # What is a function? A function is a piece of code that performs a specific task. A function is based on the input source and generates the expected output by executing a series of algorithms. # # function declaration in the Go language, the general syntax for function declarations is as follows: ' ' ' Gofunc functionname (parametername type) returntype {//function body (specifically implemented function)} ' function declaration with the keyword ' func ' Open , followed by the custom function name ' functionname ' (letter name). The parameter list of the function is defined between ' (' and ') ', and the type of the return value is defined in the following ' ReturnType (return value type) '. The syntax for declaring a parameter takes the form of a * * Parameter name * * * Argument type * *, where any number of parameters are specified as ' (parameter1 type, parameter2 type '), which is the same as (parameter 1, type of parameter 1, parameter 2, parameter 2) '. The code that is then contained between ' {' and '} ' is the body of the function. The argument list and the return value in the function are not required, so the declaration of the function below is also valid ' Gofunc functionname () {//: Indicates that the function does not require an input parameter and does not have a return value} ' # # Example function we write a function to calculate the price of a commodity, for example, the input parameter is the price of a single commodity and the number of items, the product of the product is the total price of goods, as the output value of the function. ' ' ' Gofunc calculatebill (price int, no int) int {var totalprice = Price * No//Total Product = Unit Cost * Quantity return totalprice//Total Price The above function has two integer input ' price ' and ' no ', the return value ' Totalprice ' is the product of ' price ' and ' no ', and is also an integer type. * * If there are a number of consecutive parameters, they are of the same type, then we do not need to list one by one, just add the type after the last parameter. * * For example, ' price int, ' no int ' can be abbreviated as ' price, no int ', the example function can also be written as ' ' ' ' Gofunc calculatebill (price, no int) int {var Totalprice = Price * No return totalprice} ' Now we have defined a function that we want to try to invoke in the code. The syntax for calling a function is ' functionname (parameters) '. The method for invoking the sample function is as follows: "' Gocalculatebill (10, 5) ' completes the example function declaration and invocation, we can write a complete program and print the total price of the product on the console:" ' Gopackage mainimport ("FMT") Func Calculatebill (price, no int) int {var totalprice = Price * No return Totalprice}func main () {price, No: = 90, 6// Define price and no, the default type is int totalprice: = Calculatebill (Price, no) fmt. Println ("Totalprice")///Print to console} ' [Run this Program] (Https://play.golang.org/p/YJlW3g-VZH) The program prints on the console as a result of "' Total Price is 540 "' # # Multiple return values the Go language supports a function that can have multiple return values. Let's write a function ' rectprops ' that calculates and returns the rectangular area and perimeter, with the length and width of the rectangle as the input parameter. The area of the rectangle is the product of length and width, and the perimeter is twice times the sum of the length and width. i.e.:-' area = long * width '-' perimeter = 2 * (length + width) ' ' Gopackage mainimport ("FMT") func rectprops (length, Width float64) (float64, float (+) {var area = length * Width var perimeter = (length + width) * 2 return area, Perimeter}func main () {area, perimeter : = Rectprops (10.8, 5.6) FMT. Printf ("area%f Perimeter%f", area, Perimeter)} "[Run this program] (https://play.goLang.org/p/qafte_yke_) If a function has multiple return values, these return values must be enclosed in ' (' and ') '. The ' func rectprops (length, Width float64) (float64, float64) ' example function has two input parameters for the float64 type ' length ' and ' width ' and returns the value of two float64 type. The program prints the result on the console as "area 60.480000 Perimeter 32.800000" # # # Name return value from the function you can return a named value. Once you have named the return value, you can assume that the values are declared as variables in the first line of the function. The above Rectprops function can also be written in this way: "Gofunc rectprops (length, width float64) (area, perimeter float64) {area = length * Width peri Meter = (length + width) * 2 return//Do not need to explicitly specify return value, default return area, perimeter value} "notice that the return statement in the function does not explicitly return any values. Because **area** and **perimeter** are specified as return values in the function declaration, they are automatically returned from the function when the return statement is encountered. # # white space character **_** is used as a whitespace character in Go and can be used as any value representing any type. Let's continue with the ' rectprops ' function as an example, the function calculates the area and perimeter. How do we call this function if we only need to calculate the area and don't care about the result of the perimeter calculation? At this point, the blank character **_** to play. The following program we only used the function ' Rectprops ' a return value ' area ' ' Gopackage mainimport ("FMT") func rectprops (length, Width float64) (Float64, FL Oat64) {var area = length * Width var perimeter = (length + width) * 2 return area, Perimeter}func main () {    Area, _: = Rectprops (10.8, 5.6)//return value the perimeter is lostDiscard    FMT. Printf ("area%f", area)} ' [Run this Program] (HTTPS://PLAY.GOLANG.ORG/P/IKUGSH1JIT) > in Program ' area, _: = Rectprops (10.8, 5.6) ' In this line, we see the whitespace ' _ ' used to skip the calculated results. This chapter of the tutorial is over, thank you for your reading and welcome any comments and feedback. * * Previous tutorial-[constants] (https://studygolang.com/articles/11872) * * * * Next Tutorial-[Package (Packages)] (https://studygolang.com/articles/11893) * *

via:https://golangbot.com/functions/

Author: Nick Coghlan Translator: Junedayday proofreading: Unknwon polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

4,285 reads ∙2 likes
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.