current position:Home>What are the differences between golang and python 3?

What are the differences between golang and python 3?

2022-02-02 08:24:58 Xiaoxin DS

The purpose of comparing these two languages in this paper is not to compete for who is better and who is better , Just for comparative learning , Suitable for mastering Python Want to learn Go Or master it Go Want to learn Python For your reference .

Golang and Python Are currently one of the most popular development languages in their respective fields .

Golang Its efficient and friendly Syntax , Won the favor of many back-end developers , One of the most suitable languages for high concurrency network programming .

Python Needless to say ,TIOBE The top 10 residents on the list , Now it has stabilized in the top five . Machine learning 、AI、 The field of data analysis has become a must learn language .

Both programming languages have their own characteristics in grammar , And all Easy to learn and easy to use .

Go and Python, One is static language and the other is dynamic language , From all sides , There are fundamental differences , therefore , Many contents in this article are not compared in depth , We only compare from the most intuitive syntax of programmers .

For easy reading , The codes involved in this paper are presented in simple sentences as far as possible

Character encoding

Python

Python2 The default encoding format in is ASCII Format , If the program file contains Chinese characters ( Include comments ) You need to add... At the beginning of the file # -*- coding: UTF-8 -*- perhaps #coding=utf-8 That's it

Python3 The default support Unicode

Golang

Native support Unicode

Reserved words ( keyword )

Python

30 Key words

and	exec	not
assert	finally	or
break	for	pass
class	from	print
continue global	raise
def	if	return
del	import	try
elif	in	while
else	is	with
except	lambda	yield
 Copy code 
 Copy code 

Golang

25 Key words

break	default	func	interface	select
case	defer	go	map	struct
chan	else	goto	package	switch
const	fallthrough	if	range	type
continue	for	import	return	var
 Copy code 
 Copy code 

notes

Python

#  Single-line comments 

'''
 Multiline comment 
 Multiline comment 
'''

"""
 Multiline comment 
 Multiline comment 
"""

 Copy code 
 Copy code 

Golang

// Single-line comments 

/*
 Multiline comment 
 Multiline comment 
*/
 Copy code 
 Copy code 

Variable assignment

Python

Python It's dynamic language , So when defining variables, you don't need to declare types , It can be used directly . Python Will judge the type according to the value .

name = "Zeta" #  String variable 
age = 38 #  Integers 
income = 1.23 #  Floating point numbers 
 Copy code 
 Copy code 

Multivariable assignment

a,b = 1,2 # a=1; b=2
c = d = 3 # c=3; d=3
 Copy code 
 Copy code 

Golang

Go It's a static language , It's a strong type of , however Go The language also allows the type to be determined when assigning variables .

therefore Go There are many ways to declare variables

// 1.  Complete declaration and assignment 
var a int
a = 1

// 2.  Declare variable types and assign values at the same time 
var a int = 1

// 3.  Do not declare type , When assigning values, determine 
var a = 1

// 4.  no need  var  Keyword to determine the type after declaring the variable and assigning a value 
a := 1
 Copy code 
 Copy code 

Be careful ,Go Medium new Keywords are not declared variables , Instead, it returns a pointer of that type

a := new(int) // Now a It's a *int Pointer to the variable 
 Copy code 
 Copy code 

Standard data type

Python The standard data types are :

  • Boolean( Boolean value )
  • Number( Numbers )
  • String( character string )
  • List( list )
  • Tuple( Tuples )
  • Set( aggregate )
  • Dictionary( Dictionaries )

Golang

  • boolean( Boolean value )
  • numeric( Numbers )
  • string( character string )
  • Array ( Array )
  • slice( section : Indefinite length arrays )
  • map( Dictionaries )
  • struct( Structure )
  • pointer( The pointer )
  • function( function )
  • interface( Interface )
  • channel( passageway )

summary

Python Medium List list Corresponding Go In language Slice section

Python Medium Dictionary Dictionaries Corresponding Go In language map

There are some noteworthy things :

  • Go Is a language that supports functional programming , So in Go Function is a type in language
  • Go Language is not an object-oriented language , There is no keyword defined for the class Class, To achieve OOP Style programming , It's through struct、interface Type implementation
  • Python Tuples and sets in Go None of them
  • channel yes Go A unique type in , Communication between multiple threads depends on it

Data type conversion

Python

Python Type conversion is very simple , Use the type name as the function name .

int(n)            #  The digital n Convert to an integer 
float(n)          #  The digital n Converts to a floating point number 
str(o)            #  Put the object  obj  Convert to string 
tuple(s)          #  The sequence of  s  Converts to a tuple 
list(s)           #  The sequence of  s  Convert to a list 
set(s)            #  The sequence of  s  Convert to a collection 
 Copy code 
 Copy code 

Golang

Go The basic type conversion and of language Python almost , Also use the type name as the function name

i := 1024
f := float32(i)
i = float32(f)
 Copy code 
 Copy code 

in addition ,Python Can directly convert numeric strings and numbers :

s = "123"
i = 456
print(int(s), str(i))
 Copy code 
 Copy code 

however Go no .

Go The string handling of languages is very different ,string() It can only be used for []byte Type to string , The conversion of other basic types requires strconv package , in addition , Other types are converted to string Type in addition to strconv package , You can also use fmt.Sprintf function :

package main

import (
    "fmt"
    "strconv"
)

func main() {
    s := "123"
    i, _ := strconv.Atoi(s)
    println(i)

    s2 := fmt.Sprintf("%d", 456)
    println(s2)
}
 Copy code 
 Copy code 

Go Medium interface Type cannot be directly converted to other types , Need to be used Assertion

package main

func main() {
var itf interface{} = 1
i, ok := itf.(string)
println(" value :", i, ";  assertion results ", ok)

j, ok := itf.(int)
println(" value :", j, ";  assertion results ", ok)
}
 Copy code 
 Copy code 

Output is :

 value :  ;  assertion results  false
 value : 1 ;  assertion results  true
 Copy code 
 Copy code 

Conditional statements

Python

Python The traditional judgment sentence is as follows

if name == 'zeta':          #  Determine if the variable is  zeta 
    print('Welcome boss')   #  And output welcome information 
else:
    print('Hi, ' + name)  
 Copy code 
 Copy code 

Python Ternary expressions are not supported , But a similar alternative can be used

title = "boss"
name = "zeta" if title == "boss" else "chow"
print(name)
 Copy code 
 Copy code 

Logic and use and , Logic or use or

Golang

Go Of if The syntax of is similar to Java, But the expression does not need to use ()

if a > b{
    println("a > b")
} else {
    println("a <= b")
}
 Copy code 
 Copy code 

Go Again, there is no ternary expression , And there is no alternative .

in addition ,Go Allow in if Define variables in the expression of , The expression of definition and assignment is the same as the expression of judgment ; separate , A common situation is to get the function to return error, And then determine error Is it empty :

if err := foo(); err != nil {
    println(" Something went wrong ")
} 
 Copy code 
 Copy code 

And Python Different , Logic and use &&, Logic or use ||

Loop statement

Python

Python There is while and for Two cycles , You can use break Jump out of loop and continue Immediately into the next cycle , in addition ,Python You can also use else Execute the code after the cycle is completed ,break After jumping out, it will not execute else Code for

while condition loop ,

count = 0
while (count < 9):
    print('The count is:', count)
    count = count + 1
    if count == 5:
        break   #  You can compare the following break And don't break The difference between 
        pass
else:
    print('loop over')
 Copy code 
 Copy code 

for Traversal cycle , Loop through the children of all sequence objects

names = ['zeta', 'chow',  'world']
for n in names:
    print('Hello, ' + n)
    if n == 'world':
        break
        pass
else:
    print('Good night!')
 Copy code 
 Copy code 

for You can also use... In a loop else,( Comment out the... In the code break Give it a try .)

Golang

Go Language has only one circular statement for, But according to different expressions ,for There are different performances

for  Pre expression ;  Conditional expression ;  Post expression  {
	//...
}
 Copy code 
 Copy code 

Pre expression Run... Before each cycle , It can be used to declare variables or call functions to return ; Conditional expression If the expression is satisfied, the next cycle is executed , Otherwise exit the loop ; Post expression Execute... After the loop is completed

Classic usage :

for i := 0; i < 10; i++ {
    println(i)
}
 Copy code 
 Copy code 

We can ignore pre and post expressions

sum := 1
for sum < 10 {
	sum += sum
}
 Copy code 
 Copy code 

Setting can ignore all expressions , That is, infinite loop

for {
    print(".")
}
 Copy code 
 Copy code 

Go Of for Loops can also be used break Exit the loop and continue Immediately proceed to the next cycle .

for In addition to matching expression loops , It can also be used to traverse loops , Need to use range keyword

names := []string{"zeta", "chow", "world"}
for i, n := range names {
    println(i,"Hello, " + n)
}
 Copy code 
 Copy code 

function

Python

use def Keywords define functions , And in Python in , As a scripting language , The calling function must be after the function is defined .

def foo(name):
    print("hello, "+name)
    pass

foo("zeta")
 Copy code 
 Copy code 

Default parameters Python When defining function parameters , Default values can be set , If the parameter is not passed when calling , The default value... Will be used in the function , The default value parameter must be placed after the parameter without default value .

def foo(name="zeta"):
    print("hello, "+name)
    pass

foo()
 Copy code 
 Copy code 

Key parameters When a general function passes parameters , Must be passed in the order in which the parameters are set , however Python in , Allow keyword parameters , This is done by specifying parameters , Parameters can be passed out of the order in which they are defined .

def foo(age, name="zeta"):
    print("hello, "+name+"; age="+str(age))
    pass

foo(name="chow", age=18)
 Copy code 
 Copy code 

Indefinite length parameter ,Python Support variable length parameters , use * Define parameter name , When called, multiple parameters will be passed into the function as a primitive

def foo(*names):
    for n in names:
        print("hello, "+n)
    pass

foo("zeta", "chow", "world")
 Copy code 
 Copy code 

return Returns the result of the function .

Golang

Go use func Defined function , There is no default value parameter 、 No keyword parameters , But there are many other features .

func main() {
    println(foo(18, "zeta"))
}

func foo(age int, name string) (r string) {
    r = fmt.Sprintf("myname is %s , age %d", name, age)
    return 
}
 Copy code 
 Copy code 

The definition and calling of functions are not limited in order .

Go The function can not only define the return value type of the function , You can also declare the return value variable , When the return value variable is defined , In function return The statement does not need to have a return value , The function will return... By default using the return value variable .

Variable parameters

Use … type Define variable parameters , The parameter obtained in the function is actually the type Of slice object

func main() {
	println(foo(18, “zeta”, “chow”, “world”))
}

func foo(age int, names …string) (r string) {
	for _, n := range names {
		r += fmt.Sprintf(“myname is %s , age %d \n”, n, age)
	}

	return
}
 Copy code 
 Copy code 

defer sentence

defer Specify a function after the statement , This function will be delayed until this function return Post execution .

defer Statements in Go Very useful in language , See another article in this column for details 《Golang Research and learning : How to master and make good use of defer( Delay the )

func foo() {
	defer fmt.Println("defer run")
	fmt.Println("Hello world")
	return
}
 Copy code 
 Copy code 

Running results :

Hello world
defer run
 Copy code 
 Copy code 

in addition , stay Go In language Functions are also types , Can be passed to other functions as parameters

func main() {
	n := foo(func(i int, j int) int {
		return i + j
	})
	println(n)
}

func foo(af func(int, int) int) int {
	return af(1, 2)
}
 Copy code 
 Copy code 

The above example directly uses the function type when defining parameters , It looks a little chaotic

Let's look at a clear and complete example , The instructions are all in the notes .

package main

type math func(int, int) int // Define a function type , Two int Parameters , One int Return value 

// Define a function add, This function has two int Parameter one int Return value , And math Type match 
func add(i int, j int) int {
	return i + j
}

// Let me define one more multiply, This function also conforms to math type 
func multiply(i, j int) int {
	return i * j
}

//foo function , Need one math Parameters of type , use math The function of type calculates the second 2 And the 3 A parameter number , And return the calculation results 
// Later in main We will add Functions and multiply Pass them as parameters respectively 
func foo(m math, n1, n2 int) int {
	return m(1, 2)
}

func main() {
	// Pass on add Function and two numbers , Calculate the addition result 
	n := foo(add, 1, 2)
	println(n)

	// Pass on multply And two numbers , Calculate the multiplication result 
	n = foo(multiply, 1, 2)
	println(n)
}
 Copy code 
 Copy code 

result

3
2
 Copy code 
 Copy code 

modular

Python

  • The module is a .py file
  • The module executes when it is first imported
  • An underscore defines protection level variables and functions , Two underscores define private variables and functions
  • The import module is habitually at the top of the script , But it's not mandatory

Golang

  • It has nothing to do with the file and file name , The first line of each file is marked with package Define package name , The same package name is a package
  • The variables in the package are initialized when they are first referenced , If the package contains init function , It will also be executed on the first reference ( After variable initialization )
  • Take care that capitalized functions and variables are common , Lowercase letters are private ,Golang It's not object-oriented , So there is no protection level .
  • The import module must be written in package after , Before other codes .

Import package

Python

stay Python in , Use import The import module .

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
#  The import module 
import support
 
support.print_func(“Runoob”)
 Copy code 
 Copy code 

You can also use from import Import the specified part of the module

from modname import name1[, name2[, ... nameN]]
 Copy code 
 Copy code 

Alias the imported package as keyword

import datetime as dt
 Copy code 
 Copy code 

Golang

Is also used import Import package , The import package specifies the path of the package , The package name defaults to the last part of the path

import "net/url" // Import url package 
 Copy code 
 Copy code 

Multiple packages can be used () Combined import

import (
	"fmt"
	"net/url"
)
 Copy code 
 Copy code 

Set an alias for the imported package , When importing packages directly , Add an alias directly in front of the registration , Space off

import (
	f "fmt"
  u "net/url"
)
 Copy code 
 Copy code 

Errors and exceptions

Python

Python Use classic try/except Capture exception

try:
< sentence >        # Run other code 
except < Exception name >:
< sentence >        #
except < Exception name >,< data >:
< sentence >        # If an exception with the specified name is thrown , Get additional data 
 Copy code 
 Copy code 

It also provides else and finally

If no exception occurs else Sentence block ,finally Block code executes whether or not it catches an exception

Python Built in a very comprehensive exception type name , At the same time, you can customize the exception type

Golang

Golang There is no classic try/except Capture exception .

Golang Provides two error handling methods

  1. The function returns error Type object judgment error
  2. panic abnormal

Usually in Go Only use in error Wrong type judgment ,Go Officials hope that developers can clearly control all exceptions , Return or judge in every possible exception error Whether there is .

error Is a built-in interface type

type error interface {
	Error() string
}
 Copy code 
 Copy code 

Usually , Use error Exception handling is similar to this :

package main

import "fmt"

func foo(i int, j int) (r int, err error) {
    if j == 0 {
        err = fmt.Errorf(" Parameters 2 Not for  %d", j) // to err Assign a value to a variable error object 
        return // return r and err, Because the return value variable name is defined , So you don't need to write the return variable here 
    }

    return i / j, err // If there is no assignment error to err Variable ,err yes nil
}

func main() {
    // Pass on add Function and two numbers , Calculate the addition result 
    n, err := foo(100, 0)
    if err != nil { // Judge the returned err Is the variable nil, If not , Description function call error , Print error content 
        println(err.Error())
    } else {
        println(n)
    }
}
 Copy code 
 Copy code 

panic It can be called manually , however Golang The official advice is not to use panic, Every exception should use error Object capture .

Go In some cases, language triggers built-in panic, for example 0 except 、 Array out of bounds, etc , Modify the example above , Let's let the function cause 0 except panic

package main

func foo(i int, j int) (r int) {
	return i / j
}

func main() {
	// Pass on add Function and two numbers , Calculate the addition result 
	n := foo(100, 0)
	println(n)
}
 Copy code 
 Copy code 

After running, it will appear

panic: runtime error: integer divide by zero
goroutine 1 [running]:
main.foo(...)
        /lang.go:4
main.main()
        /lang.go:9 +0x12
exit status 2
 Copy code 
 Copy code 

manual panic It can be like this :

func foo(i int, j int) (r int) {
	if j == 0 {
		panic("panic explain : j by 0")
	}
	return i / j
}
 Copy code 
 Copy code 

After operation , You can see , The first sentence of the error message :

panic: panic explain : j by 0
 Copy code 
 Copy code 

object-oriented

Python

Python Fully support object-oriented .

Golang

Even though Go The language allows object-oriented style programming , But it's not object-oriented in itself

official FAQ original text

Is Go an object-oriented language?

Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of “interface” in Go provides a different approach that we believe is easy to use and in some ways more general. There are also ways to embed types in other types to provide something analogous—but not identical—to subclassing. Moreover, methods in Go are more general than in C++ or Java: they can be defined for any sort of data, even built-in types such as plain, “unboxed” integers. They are not restricted to structs (classes).

Multithreading

Python

  1. Use thread Module start_new_thread() function
  2. Use threading Module creation thread

Golang

Use key go Create coroutines goroutine

stay go Keyword to specify the function , A coroutine will be opened to run the function .

package main

import (
    "fmt"
    "time"
)

func foo() {
    for i := 0; i < 5; i++ {
        fmt.Println("loop in foo:", i)
        time.Sleep(1 * time.Second)
    }
}

func main() {
    go foo()

    for i := 0; i < 5; i++ {
        fmt.Println("loop in main:", i)
        time.Sleep(1 * time.Second)
    }
    time.Sleep(6 * time.Second)
}
 Copy code 
 Copy code 

Go In language , The communication between processes is through channel Realized :

package main

import (
    "fmt"
    "time"
)

// Accept one chan Parameters of type c
func foo(c chan int) { 
    time.Sleep(1 * time.Second) // wait for 1 second 
    c <- 1024                   // towards c Write a number in 
}

func main() {
    c := make(chan int) // establish chan Variable c
    go foo(c)           // Run the function in the subroutine foo, And pass the variable c
    fmt.Println("wait chan 'c' for 1 second")
    fmt.Println(<-c) // Take out chan 'c' Value ( When the value is taken , If c No value in , The main county will block waiting )
}
 Copy code 
 Copy code 

summary

Python and Go It is one of the most easy to learn and use programming languages in dynamic language and static language respectively .

There is no substitution relationship between them , But each plays its own role in its field .

Python The syntax is simple and intuitive , In addition to being loved by programmers, it is also very suitable for practitioners in other fields .

Go It has both simple syntax and efficient operation , Excellent in multithreading , It is very suitable for students who have mastered a certain programming foundation and a mainstream language , however ,Go Object oriented is not supported , For most users who support object-oriented languages, they are learning Go When it comes to language , You need to remember and change your programming ideas .

copyright notice
author[Xiaoxin DS],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020824521189.html

Random recommended