Home  >  Article  >  Backend Development  >  python translated to golang

python translated to golang

王林
王林Original
2023-05-10 11:15:36765browse

Preface

Python is a widely used high-level programming language. It is easy to learn and use, has concise code, and has high development efficiency. It has been widely used in data science, machine learning and other fields. Go language is a rising star with better concurrency performance and higher code running efficiency. Therefore, when we need to improve the running efficiency of Python code or make better use of computer multi-core resources, we can use Go language to write more efficient programs.

This article mainly introduces how to translate Python code into Go language, and discusses how to design and optimize Go language programs from the perspective of Python functions.

1. Translation of Python code into Go language

Before translating Python code into Go language, you need to understand the differences and similarities between the two languages. Python is a dynamically typed language that emphasizes code readability and simplicity. Go language is a statically typed language that focuses on code maintainability and concurrent processing capabilities.

There are two ways to translate Python code into Go language. One is to manually write Go language code and implement the corresponding Go language function according to the logic of the Python program. The second is to use existing translation tools, such as py2go and transcrypt.

Manual writing of Go language code

The following introduces some examples of translating Python code into Go language code in order to better understand the relationship between the two languages.

Python code:

def fib(n):
    if n <= 1:
        return n
    else:
        return (fib(n-1) + fib(n-2))

print([fib(i) for i in range(10)])

Go language code:

package main

import "fmt"

func fib(n int) int {
    if n <= 1 {
        return n
    } else {
        return (fib(n-1) + fib(n-2))
    }
}

func main() {
    for i := 0; i < 10; i++ {
        fmt.Printf("%d ", fib(i))
    }
}

Here is another example:

Python code:

def merge_sort(lst):
    if len(lst) <= 1:
        return lst
    mid = len(lst) // 2
    left = merge_sort(lst[:mid])
    right = merge_sort(lst[mid:])
    return merge(left, right)

def merge(left, right):
    result = []
    i, j = 0, 0
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result += left[i:]
    result += right[j:]
    return result

print(merge_sort([3, 1, 4, 2, 5]))

Go Language code:

package main

import "fmt"

func mergeSort(lst []int) []int {
    if len(lst) <= 1 {
        return lst
    }
    mid := len(lst) / 2
    left := mergeSort(lst[:mid])
    right := mergeSort(lst[mid:])
    return merge(left, right)
}

func merge(left []int, right []int) []int {
    result := []int{}
    i, j := 0, 0
    for i < len(left) && j < len(right) {
        if left[i] < right[j] {
            result = append(result, left[i])
            i++
        } else {
            result = append(result, right[j])
            j++
        }
    }
    result = append(result, left[i:]...)
    result = append(result, right[j:]...)
    return result
}

func main() {
    lst := []int{3, 1, 4, 2, 5}
    fmt.Println(mergeSort(lst))
}

Use translation tools for code conversion

Using translation tools can reduce the time and workload of handwritten code. For example, use the py2go translation tool to convert the above Python code into Go language code:

Python code:

def fib(n):
    if n <= 1:
        return n
    else:
        return (fib(n-1) + fib(n-2))

print([fib(i) for i in range(10)])

Go language code:

package main

import (
    "fmt"
)

func fib(n int) int {
    if n <= 1 {
        return n
    } else {
        return (fib(n-1) + fib(n-2))
    }
}

func main() {
    var lst []int
    for i := 0; i < 10; i++ {
        lst = append(lst, fib(i))
    }
    fmt.Println(lst)
}

2. Design and optimize Go language programs from the perspective of Python functions

From the perspective of Python functions , we can optimize Go language programs in the following ways.

  1. Type declaration of initial parameters

Go language is a statically typed language, and parameter types need to be declared when the function is defined. At the same time, the parameter passing method of Go language is value passing, while the parameter passing method of Python is reference passing.

Python code:

def add(x, y):
    x.append(y)
    return x

lst = [1, 2, 3]
print(add(lst, 4))    # [1, 2, 3, 4]
print(lst)            # [1, 2, 3, 4]

Go language code:

func add(x []int, y int) []int {
    x = append(x, y)
    return x
}

func main() {
    lst := []int{1, 2, 3}
    fmt.Println(add(lst, 4))    // [1 2 3 4]
    fmt.Println(lst)            // [1 2 3]
}

In Go language, parameters need to be declared as slice types so that they can be modified in the function.

  1. Use of blank identifiers

Using blank identifiers _ in Go language can represent anonymous variables. For example, in Python, underscore _ is usually used to replace a variable name. Indicates that this variable will not be referenced in subsequent uses.

Python code:

x, _, y = (1, 2, 3)
print(x, y)    # 1 3

Go language code:

x, _, y := []int{1, 2, 3}
fmt.Println(x, y)    // 1 3

In Go language, use underscore _ to represent anonymous variables, but its scope is the current statement block. For example, when assigning a value to underscore_, the value is discarded.

  1. Interface-oriented programming

For polymorphism, Python has a built-in duck-typing feature, that is, the applicability of an object is not based on its type, but Based on the methods it has. In Go language, you can use interfaces to achieve polymorphism.

For example, in the following code, both Cat and Dog implement the Say method in the Animal interface, so there is no need to care about the actual type of the object in the Test function, only whether it implements the Animal interface.

Python code:

class Animal:
    def say(self):
        pass

class Cat(Animal):
    def say(self):
        return 'meow'

class Dog(Animal):
    def say(self):
        return 'bark'

def test(animal):
    print(animal.say())

test(Cat())    # meow
test(Dog())    # bark

Go language code:

type Animal interface {
    Say() string
}

type Cat struct {
}

func (c *Cat) Say() string {
    return "meow"
}

type Dog struct {
}

func (d *Dog) Say() string {
    return "bark"
}

func Test(animal Animal) {
    fmt.Println(animal.Say())
}

func main() {
    Test(&Cat{})    // meow
    Test(&Dog{})    // bark
}
  1. Supports optional parameters and default parameters

In Python, The writing method that supports optional parameters and default parameters is very flexible. You can specify default values ​​in the function definition, or use args and *kwargs to pass optional parameters.

Python code:

def func(a, b=10, *args, **kwargs):
    print(a, b)
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(key, value)

func(1)    # 1 10
func(2, 3)    # 2 3
func(4, 5, 6, 7, eight=8, nine=9)    # 4 5 6 7 eight 8 nine 9

In the Go language, due to the support for function overloading, the parameter list of a function can define different types of parameters as needed. For example, in the following code, overloading is used to implement optional parameters and default values.

Go language code:

func Func(a int, b int) {
    fmt.Println(a, b)
}

func Func2(a int, b int, args ...int) {
    fmt.Println(a, b)
    for _, arg := range args {
        fmt.Println(arg)
    }
}

func Func3(a int, kwargs map[string]int) {
    fmt.Println(a)
    for key, value := range kwargs {
        fmt.Println(key, value)
    }
}

func main() {
    Func(1, 10)    // 1 10
    Func(2, 3)    // 2 3
    Func2(4, 5, 6, 7)    // 4 5 6 7
    kwargs := map[string]int{"eight": 8, "nine": 9}
    Func3(4, kwargs)    // 4 eight 8 nine 9
}

Summary

This article introduces how to convert Python code into Go language code, and from the perspective of Python functions, discusses how to declare parameters Types, using whitespace identifiers, interface-oriented programming, and overloading to implement optional parameters and default values ​​are ways to optimize Go language programs. Both Python and Go languages ​​have their own characteristics, advantages and disadvantages, and the specific choice of which language needs to be considered based on the specific situation. Finally, thank you for reading!

The above is the detailed content of python translated to golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn