Home Backend Development Golang python translated to golang

python translated to golang

May 10, 2023 am 11:15 AM

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)])
Copy after login
Copy after login

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))
    }
}
Copy after login

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]))
Copy after login

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))
}
Copy after login

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)])
Copy after login
Copy after login

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)
}
Copy after login

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]
Copy after login

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]
}
Copy after login

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
Copy after login

Go language code:

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

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
Copy after login

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
}
Copy after login
  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
Copy after login

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
}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang vs. C  : Performance and Speed Comparison Golang vs. C : Performance and Speed Comparison Apr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

C   and Golang: When Performance is Crucial C and Golang: When Performance is Crucial Apr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

See all articles