In 2024, Rust is becoming more and more popular

In 2024, Rust is becoming more and more popular

On February 19th, Rust released its 2023 survey report. This survey has been conducted continuously for eight years, attracting many maintainers, contributors, and people interested in the future development of Rust projects to participate.

The 2023 Rust Status Survey began on December 18, 2023 and will continue until January 15, 2024. The Rust team is exploring a more efficient and sustainable process to collect and analyze data faster, providing deeper and more valuable insights to the community.

# Rust Usage

In 2023, the proportion of respondents who identify themselves as Rust users will increase slightly, from 91% in 2022 to 93% in 2023.

img

Among the population using Rust in 2023, 49% are using Rust every day, an increase of 2 percentage points compared to last year, showing a slight upward trend.

img

Among respondents who were non-Rust users , 31% said the difficulty of Rust was the main reason they didn’t use it, while 67% noted that they haven’t had the opportunity to prioritize learning Rust, which remains the most common reason they don’t use Rust.

img

Among former Rust users surveyed in 2023, 46% said they stopped using Rust due to factors beyond their control (down 1 percentage point from 2022), 31% gave up Rust due to a preference for other programming languages (up 9 percentage points from 2022), and 24% cited difficulty as the main reason they gave up Rust (down 6 percentage points from 2022).

img

In the past year, the level of Rust skills among respondents has generally improved! 23% of people can write simple Rust programs (a decrease of 6 percentage points compared to 2022), 28% of people can write code that can be used in actual production (an increase of 1 percentage point), and 47% of people believe that they are quite efficient when using Rust - this proportion has increased from 42% in 2022. Although this survey is only one of many tools to measure changes in Rust skill levels, these numbers are still encouraging because they reflect the increasing knowledge and skills of Rust users who participate in the survey year after year.

img

From the perspective of the operating system used by Rust users, the current situation is roughly the same as the survey results in 2022. Linux is still the most popular choice among Rust users, followed closely by macOS and Windows, with similar usage rates among the three.

img

While Linux machines remain the favorite platform for Rust programmers, they are also developing Rust programs for a variety of other platforms. Notably, the number of users for WebAssembly, embedded, and mobile platforms has increased slightly, further highlighting Rust’s Cross-Platform Capability.

img

From the current situation, Visual Studio Code seems to still be the most popular editor among Rust developers, and RustRover, launched last year, has also won the favor of many developers.

img

# Rust work

The trend of using Rust in work continues to rise year by year. In the 2023 survey, 34% of respondents said they use Rust for most of their coding work, an increase of 5 percentage points from 2022. Among this group, 39% of people’s organizations have a significant application of Rust.

img

It is worth noting that the top reason for employers to invest in Rust among respondents is still the ability to build relatively accurate and defect-free software, accounting for as high as 86%. This proportion has increased by 4 percentage points compared to the survey results in 2022. Rust’s performance characteristics ranked second, accounting for 83%.

img

We are also pleased to see that 79% of respondents stated that Rust has helped their company achieve its established goals, an increase of 7 percentage points compared to 2022. In addition, 77% of respondents expect their organization to continue using Rust in the future, an increase of 3 percentage points from the previous year. It is worth mentioning that the proportion of respondents who believe that Rust is challenging for their organization has decreased, from 34% in 2023 to 39% in 2022. At the same time, the proportion of respondents who believe that Rust’s investment value for money has also increased, from 60% in 2022 to 64% in 2023.

img

The formation of this trend is influenced by various factors, but the continuous improvement of Rust’s popularity may have led to the abundance of resources, which in turn provides better support for new teams using Rust. In terms of technology, Rust has shown obvious advantages in building server backends, web and network services, and cloud technology, and has been widely welcomed.

img

# Rust Challenge

The Ruts team has been working to reveal the challenges, concerns, and priorities Rustaceans have faced throughout the year through the Rust Status Survey.

Among the 9,374 respondents who shared their concerns about the future of Rust, we noticed that the majority (43%) are concerned that Rust will become too complex, an increase of 5 percentage points from 2022. In addition, 42% of respondents are concerned about the insufficient popularity of Rust in the technology industry. It is particularly noteworthy that in 2023, 32% of respondents are most concerned that Rust developers and maintainers will not receive sufficient support, an increase of 6 percentage points from 2022.

It is gratifying that the proportion of respondents who are not worried about the future of Rust has significantly decreased, from 30% in 2022 to 18% in 2023.

img

The features that Rust users want to implement, stabilize, or improve are mainly in the following areas: features (such as trait aliases, associated type defaults, etc.), constant execution (such as generic constant expressions, constant attribute methods, etc.), and asynchronous programming (such as asynchronous closures, coroutines, etc.). These areas are all important areas of improvement that the Rust community is currently focusing on and expecting.

img

It is worth noting that 20% of respondents said they hope Rust can slow down the development of new features, which is likely related to the concerns mentioned earlier about Rust becoming too complex.

From the survey results, it seems that Rustaceans are most likely to encounter challenges in asynchronous Rust, feature and generic systems, and borrow checkers. These areas require more support and improvement to meet the needs and expectations of the community.

img

The respondents who participated in the survey expect Rust maintainers to mainly focus on the following aspects: the top priority is to fix vulnerabilities in the compiler (68%), followed by improving the runtime performance of Rust programs (57%) and improving compile time (45%). Improvements in these key areas will help improve the overall quality and User Experience of Rust.

img

Similar to the situation in recent years, respondents generally believe that compile time is one of the key areas that urgently needs improvement. However, it is worth noting that respondents seem to value the importance of runtime performance more when weighing runtime performance against compile time. This indicates that optimizing runtime performance is also an important issue of concern in the Rust community.

So the question is, will you embrace Rust?

2024 Rust Developer Roadmap

2024 Rust Developer Roadmap

In the past five years, Rust has become one of the 15 most popular and beloved programming languages with its incredible development experience and flexibility. It has powerful features, transparent documentation, and a participatory and supportive community of contributors.

Rust prioritizes safety, performance, and concurrency. It allows programmers to use the control of low-level languages to create applications, while also possessing the powerful abstraction of high-level languages. Overall, with Rust, you can do many things, so every developer should at least give it a try.

img

The core content of this article is as follows:

# 1. Rust Core Features

Below we will explore some core features of Rust

Memory safety:

The main design goal of Rust is to ensure memory safety without relying on the garbage collector. This is achieved through transparent data ownership, a powerful type system, and strict compile-time checks. The data ownership paradigm stipulates that each piece of data in Rust has a unique owner. When ownership is transferred (called “moved”), the previous owner can no longer access the data. This can prevent duplicate release operations and eliminate double deletion errors. This method eliminates a class of errors during the compile phase.

By using the Option < T > type in Rust, errors such as null pointer backreferences that are common in many languages can be eliminated. It explicitly handles the situation where a value may not exist.

Due to Rust’s borrowing and ownership system, it can also prevent data races and buffer overflows. If a piece of code may be unsafe, Rust will not compile it unless it is wrapped in an unsafe block to remind developers to operate with caution.

Concurrency model:

Concurrency in Rust is built on the same principles that provide memory safety: ownership and borrowing. By utilizing these principles, Rust ensures thread safety.

The language provides several concurrency primitives such as Arc (atomic reference counting) for shared state and Mutex or RwLock for mutable access. Channels in Rust provide a way for communication between threads.

The async/await syntax introduced 1.39.0 Rust allows you to write asynchronous code that looks like synchronous code, simplifying complex concurrency scenarios.

Excellent performance:

Rust’s “zero-cost abstraction” means that using advanced constructs does not incur runtime overhead. You can reap the benefits of abstraction without sacrificing performance.

As a systems language, Rust provides extensive control over hardware resources. This makes it as efficient as C and C++ in many benchmarks, with added security guarantees.

Since Rust is explicit and has no runtime, it can perform internal connections, loop unwinding, and other aggressive optimizations.

# 2. Advantages of Rust

img

Rust combines various programming styles: procedural, Actor-based concurrency, Object Oriented, and pure function. It also supports general and metaprogramming in static and dynamic forms. Here is an overview of the main advantages of Rust.

Easy to deploy:

Without active use, Rust’s powerful security and integrity tools are meaningless. The creators and community of Rust make it easy for beginners to master this language. The software packages required to generate Rust binary files are unified. Only when working with components outside the Rust system (such as compiling C libraries from source code), external compilers like GCCO are needed.

Powerful type system:

Using Rust, compiling code with detectable errors is not allowed. This feature allows developers to focus on the core logic of the program rather than correcting the problem.

Cross-platform compatibility:

Although Rust is compatible with most modern platforms, its developers did not aim to make it a universal language, but focused on popular platforms. Rust can run on three main operating systems: Linux, Windows, and MacOS. If cross-compiling or generating binary files for another platform or architecture is required, Rust is also relatively easy to implement.

Powerful features:

Rust has a set of native features comparable to C++: macros, generics, pattern matching, and composition through “features”.

Comprehensive standard library:

One of Rust’s broader goals is to provide alternatives comparable to C and C++. Therefore, it provides a wide range of standard libraries including containers, collections, iterators, string operations, process and thread management, etc. As Rust aims to be cross-platform, its standard library only includes general portable features. Platform-specific functions can be obtained through third-party libraries. In addition, Rust can run without a standard library, which is particularly useful when developing platform-independent binaries such as embedded systems.

Selection of third-party libraries:

The versatility of a language often depends on the third-party support it receives. Rust’s official repository Cargo hosts over 60,000 “crates”, many of which are API bindings of popular libraries or frameworks. However, these crates do not have a comprehensive ranking system based on quality, so you must rely on personal experience or community advice.

IDE support:

The Rust team developed rust-analyzer, which can provide real-time feedback from Rust compilers to IDEs, such as Microsoft Visual Studio Code.

Open source:

As an open-source language, Rust benefits from the contributions of a global developer community, constantly improving its performance. It is especially friendly for beginners. It also regularly updates detailed and transparent language documentation.

# 3. Rust ecosystem

img

One important advantage of Rust is its extensive ecosystem of tools, frameworks, and libraries.

Cargo:

Cargo is the official package manager and compiler for Rust. It handles project building, dependency management, and test execution. Developers use crates.io as the official regedit for Rust packages, managed by the Rust community and integrated with Cargo.

Rustup:

Rustup is a tool that simplifies Rust version management, allowing you to switch and update between different Rust toolchains.

Development Environment:

Many Integrated Development Environments (IDEs) and text editors now support Rust development, including Visual Studio Code, Atom, and IntelliJ IDEA.

Libraries and Frameworks:

Rust’s library and framework ecosystem continues to expand, covering applications such as web development, gaming, and Machine Learning. Some popular libraries and frameworks include Rocket, Tokio, Serde, and Actix.

Rust-analyzer:

Rust-analyzer is an efficient and reliable language server that provides features such as code analysis and auto-completion for Rust code. It is easy to use and compatible with multiple text editors and IDEs.

Rustfmt is a formatting tool specifically designed to ensure uniform formatting of Rust code.

Rich learning resources:

Rust provides a lot of useful documentation. Here are some useful resources collected:

  • The Rust Programming Language Book (in-depth explanation of Rust and its core concepts)
  • Rust Language Cheat Sheet
  • Rust Atomics and Locks. Low-Level Concurrency in Practice by Mara Bos (book)
  • Programming Rust: Fast, Safe Systems Development by by Jim Blandy, Jason Orendorff, Leonora Tindall (book)
  • Rust by Example (collection of annotated code samples)
  • Rust Install documents
  • Rust Installer download page
  • Rust design patterns
  • Rust in Motion (paid video course)
  • Rust in blockchain (weekly newsletter)
  • Serokell’s selection of the best Rust learning resources

# 4. Rust development roadmap

img

# 5. Challenges of Rust development

Rust programming language provides many advantages, such as enhanced security, excellent performance, simplified concurrency programming, and ensuring memory safety. However, Rust is not without its drawbacks. Some common challenges when using Rust include:

  • Steep learning curve: For beginners, concepts such as ownership, borrowing, and lifecycle in Rust can be confusing, especially for those who have not been exposed to these concepts.
  • Lengthy syntax: Some people criticize the language’s verbose syntax, which can be seen as both an advantage (explicit rather than implicit) and a disadvantage (requiring verbose code to implement simple tasks).
  • Limited libraries: While the Rust ecosystem is growing rapidly, it lags behind more mature languages like Python, Java, or JavaScript in terms of the number and diversity of third-party libraries.
  • Compile time: A frequently mentioned disadvantage is the long compile time. This may slow down development speed, especially in larger projects.
  • Maturity: Although Rust is a stable language, it is still younger than many competitors. Therefore, certain features and best practices are still evolving.
  • Simplified runtime: This is both an advantage and a challenge. Although it allows Rust to be used in system programming and resource-constrained environments, it also means that the language does not have as many built-in features as languages with more complete runtimes.

# Finally

A survey shows that Rust is becoming more and more popular among developers. The 2023 Stack Overflow Developer Survey shows that 13% of people have extensive work experience on Rust recently, and from 2016 to 2023, this language has been the “most popular”. Rust also ranks sixth in the “most popular technology” in 2023.

The combination of advanced abstraction and fine grain control makes Rust the preferred choice for developing safe and efficient system software. With the increasing recognition of Rust in the developer community, it may become the dominant language in more fields.

2024 React Trends

2024 React Trends

# 2024 React Trends

With the rapid development of technology, React, as a leading front-end framework, has won widespread recognition and application worldwide. Looking ahead to 2024, how will the development trend of React evolve? This article will analyze the potential changes of React in future technology dynamics, application areas, and community ecology, in order to provide valuable reference and inspiration.

# React 19 is coming

After more than 600 days of suspension, React revealed in its blog that it will release React 19 in 2024. The article also mentioned that the React team is developing a new compiler that will automate all caches in React applications. This means that the process of manually caching functions ( useCallback ), values ( useMemo ), and components ( memo ) in the past is expected to be eliminated in the future. React will be responsible for handling these caches, thus avoiding recalculating everything every time it is rendered.

After the release of React 19, these APIs may no longer be needed.

  • useMemo , useCallback , memo → React Compiler: React’s new compiler will replace these hooks for optimization and caching.
  • forwardRef ref as a prop : ref will be passed directly as a property, no longer forwardRef .
  • React.lazy → RSC, promise as child element: The lazy loading function of React will be replaced by RSC or components with child element Promise.
  • useContext use (Context) : (Using Context will become more concise, possibly through a new use function.
  • Throw promise → use (promise) : There will be a new use function for handling exceptions thrown in Promises.
  • < Context. Provider > < Context > : Providing Context will become more concise and may be implemented directly through the Context component.

# Astro + React

Last year, Astro emerged as a strong competitor to Gatsby, initially targeting static website design. However, due to its rapidly accumulating popularity and growing functionality, Astro began actively exploring the possibilities of web applications and API endpoints. Although Astro remains an ideal choice for high-performance websites, web developers have also begun to consider applying it to a wider range of use cases beyond its original scope.

Astro-built websites have high performance by default because they avoid unnecessary JavaScript from scratch and transfer high-cost rendering work to the server. Although static site generation (SSG) is the default option, server-side rendering (SSR) can still be selected.

Astro is not limited to React. You can directly use Astro’s native way to build UI components in the “.astro” file without the need for a UI framework. At the same time, Astro is also compatible with various component frameworks, such as React, allowing you to fully utilize your rich experience to create rich and exquisite UI components.

Even when used in conjunction with frameworks like React, Astro does not introduce JavaScript and only transmits HTML and CSS to the browser. Only when components need to interact, the server will send necessary JavaScript to the client on demand. All of this is closely related to Astro’s “default high performance” concept, driven by its rendering mode called Island architecture.

img

With the help of Astro, the achieved projects not only demonstrate excellent performance and SEO scores, but also feature beautiful themes and convenient document functions provided by Astro Starlight. In the future, this advanced method will gradually become the mainstream standard for website construction. Looking forward to Astro continuing to bring me unprecedented innovation and infinite possibilities in the future.

# Build tools: Vite vs Turbopack

Turbopack was jointly created by the founders of Vercel and Webpack, aiming to be the successor to Webpack. Although it has not yet been fully put into production, it has shown its potential in the local Development Environment of Next.js. Turbopack not only brings together the experience accumulated by Webpack for many years, but also achieves a qualitative leap through a new architecture based on Rust. For example, Tree Shaking and caching functions that were once overlooked in Webpack have received key support in Turbopack.

img

With the development of technology, the role of building tools has become increasingly important. The interweaving of client and server level components, intelligent caching of application entry points, and the demand for component-level data acquisition have all put forward higher requirements for building tools. Therefore, Vercel deeply feels the need for a new type of building tool to cope with these challenges.

Personally, I had hoped that Vite and its powerful server-level capabilities could be integrated into Next.js. However, despite Vite being favored by many meta-frameworks (such as Remix) and Single Page Applications in the past year, the Vercel/Next team chose to develop Turbopack as their solution. This decision undoubtedly demonstrates their pursuit of technological innovation and unique insights into future packaging technology.

# React state management

Although React state management has been a long-standing topic, with the emergence of new solutions (such as Signals, Zustand, and Recoil), they handle state management in a different way from traditional methods (such as Redux and React Hooks), making it still a hot topic in the React developer community. Let’s briefly review the two main competitors below.

  • Redux, as a state container for JS applications, is closely integrated with React through React-Redux. However, developers have different opinions on the utility of Redux. Some believe that it is still a powerful tool for state management, while others believe that although it is effective, it is not always necessary, especially in small and medium-sized applications. With the continuous development of the React ecosystem, there seems to be a consensus forming: Redux is more suitable for large and complex applications.
  • React Hooks (such as useState and ReactContext ) provide a neat solution for sharing state across applications. However, there are certain rules to follow when using Hooks, which can be confusing for beginners and even difficult for experienced developers to achieve perfect state management.

Due to these complexities and potential limitations, more and more developers are looking for lighter and more concise state management solutions. For example, Zustand is a library worth paying attention to, which solves problems in a similar way to Redux, but with less code and easier understanding and use. In fact, Zustand topped the list of state management libraries in this year’s JavaScript Rising Stars Report, which fully demonstrates its popularity and potential.

img

Besides Zustand, there are other high-profile state management libraries such as Recoil, MobX, and Jotai. These libraries each have unique features and advantages, providing React developers with more choices and possibilities.

img

Signals, a state management pattern that has been around for several years, has still sparked heated discussions in the React community. Through the Preact library, Signals now supports React, aiming to solve the pain points of Hooks and complex state management libraries such as Redux. It simplifies the process of storing and updating values across applications, and only renders components that have changed, improving efficiency.

In 2024, React state management may evolve towards lightweight, integration and compatibility, better developer experience, customization and flexibility, and integration with other technologies.

# React Server Components and Next.js

React Server Components (RSCs) is a new specification launched by the React team, including its underlying implementation. It was implemented and first adopted by the community through version 13.4 of Next.js last year. Regardless of external discussions and challenges, RSCs undoubtedly brought a huge paradigm shift to web development.

img

Compared to React Hooks, RSCs may bring more profound changes because they encourage developers to rethink how to use React components in large applications. In Next.js and its new App Router, RSCs have become the new standard for every React developer. As more and more frameworks (even beyond the boundaries of React) explore the adoption (and implementation) of Server Components, emerging small frameworks such as Waku have taken the lead in implementing this technology.

This new architecture brings many advantages. Although it is difficult to list them one by one, an example can be given to illustrate: RSCs allow developers to perform component-level data acquisition on the server before sending components to the browser (or through streaming). This means that the once troublesome client-to-server network waterfall requests have become history. Nowadays, these requests (if they exist) are completed more quickly on the server, significantly improving performance.

Emphasizing the advantage of RSCs is crucial because it reveals how the React ecosystem must adapt to it. Tools such as tRPC and react-query play a key role in client-server communication. However, in a world without APIs, what role these tools will play when RSCs perform most data retrieval on servers has become a key issue. Although some Proof of Concept have emerged, we still look forward to how this field will continue to develop in 2024.

# Biome

Although ESLint and Prettier play a crucial role in web development, their setup and collaboration processes often make developers feel tricky. Nevertheless, these tools are still essential for daily work. Biome (formerly known as Rome) is committed to breaking new ground in this field by providing fast and comprehensive toolchain solutions. Another highly anticipated all-in-one toolchain is oxc.

Biome won a $20,000 prize from Prettier for its ability to create more efficient formatters in Rust. However, it remains to be seen whether developers will adopt this new tool. Meanwhile, discussions about getting rid of the strict dependence on ESLint and allowing the use of other linters are raging on multiple platforms, such as the Next.js GitHub discussion area.

img

I am looking forward to this project. If it succeeds, it may become an efficient toolchain that drives all the necessary functions of modern web application development.

# TanStack Router Helps Build Single Page Applications

Despite the increasing popularity of React Server Components, Tanner Linsley, the main promoter of popular React libraries such as react-query and r eact-table, believes that Single Page Application (SPA) is not outdated. Recently, he has released a new library: TanStack Router.

img

The release timing of TanStack Router is just right, filling an important gap in the React ecosystem. Although many developers have adopted meta-frameworks such as Next.js and Remix (which have built-in routers and focus on implementing RSCs), so far, no one has created type-safe routes for React.

With TypeScript becoming an industry standard in the past few years, I am excited about this new router in the React ecosystem because it provides excellent TypeScript support. For example, it will allow developers to read and write URL states in a type-safe manner. Perhaps this new router will also push other mature routers to meet these top TypeScript standards.

# React Authentication

With multiple startups and open source projects entering the identity verification field, the identity verification function in React has ushered in new vitality. For a long time, solutions such as Firebase Authentication, Auth0, Passport.js, and NextAuth have been firmly in the mainstream position, but now we have ushered in a new cost-effective alternative driven by User Interface.

Supabase, as an open-source alternative to Google Firebase, not only provides comprehensive authentication capabilities, but also integrates diverse tools such as PostgreSQL database, real-time subscription, storage, and serverless functions. It can be self-hosted or used as a paid service. Although many developers use Supabase for authentication, in other fields, they may choose more suitable services, such as PlanetScale as a serverless database.

img

Clerk focuses on the field of identity verification, making the user registration and login process easy and convenient through the Plug and Play component provided for React. In addition, Clerk also provides user management and role assignment functions, supporting single or multiple organizations. For startups, Clerk is undoubtedly an ideal choice for building Minimum Viable Products (MVP).

Finally, we cannot ignore the power of Lucia. Although it is popular due to its combination with Astro, it can also play a role in other frameworks. Lucia’s open source nature, community support, and clear abstraction layer between applications and databases are impressive. Especially its ability to manage users in its own database is undoubtedly a huge advantage compared to other authentication services.

# React Headless UI Library

The React community’s choice of UI libraries has been changing year by year. From Material UI a few years ago, to Semantic UI/Ant Design, to Chakra UI and Mantine UI, and finally last year, the focus was on shadcn/UI. Although these choices are based on design and usability considerations, shadcn/UI has shown its uniqueness.

Shadcn/UI has become a popular UI library, innovatively using Tailwind as a core component (alongside CSS variables) for theme customization to achieve highly customizable design goals. Unlike conventional installation methods, shadcn/UI is not installed as a Node package, but directly copied and pasted into the project, allowing developers to freely adjust components to meet unique needs.

img

The trend of this headless UI library did not originate from shadcn/UI, but from developers’ desire for unique design and User Experience. When relying on popular UI libraries, achieving unique designs often faces challenges.

It is worth mentioning that in order to improve performance and User Experience, more and more components are being rendered on the server side. This trend limits the use of CSS-in-JS solutions (such as Styled Components and Emotion), as these solutions rely on the Client/Browser to execute JavaScript to generate CSS, increasing the performance burden. In contrast, emerging CSS-in-JS solutions (such as StyleX) effectively solve this problem by compiling CSS as a practical priority.

With the development of this trend, we look forward to seeing more innovative UI libraries and CSS paradigms emerge. Currently, headless UI libraries (such as Radix and shadcn/UI) and practical CSS (such as Tailwind) have emerged, and in the future, there may be more alternatives such as vanilla-extract, PandaCSS, CVA, etc., providing more choices and possibilities for web developers.

Rust is fully invading the front-end

Rust is fully invading the front-end

# Rust is fully invading the front-end

I have studied the basics of Rust and some ecological technical solutions solidly and systematically. The original intention of learning it is because Rust can support the native-level development of HarmonyOS applications and provide technical reserves for advanced HarmonyOS developers.

But if you don’t learn, you won’t know, and you’ll be shocked when you learn. Only then did you realize that the Rust ecosystem is invading all aspects of front-end development with an unstoppable momentum, all-round and no dead ends . The most critical thing is that due to the latecomer advantage, these technical solutions are often more advanced, more scientific, and have higher performance than existing front-end solutions…

# Farm

img

Farm is an extremely fast build engine written in Rust. In its promotional documentation, it claims to be more than 10 times faster than Webpack and 5 times faster than Vite. Obviously, this is a front-end project build tool that wants to accurately target Vite.

Due to Vite adopting a compile-on-request strategy for modules in the project and not bundling the source code, according to the experience of the Byte Architecture team, when the project is huge, the first page loading time of Vite may be as long as tens of seconds “when the page is first loaded, a large number of modules are loaded”, it is extremely slow when refreshing, and the huge request volume may cause the browser to crash, affecting the development experience.

And vite in the Development Environment using esbuild pre-compile, in the generation environment using bundler rollup, the processing is different, occasionally there may be Development Environment and online behavior inconsistent situation , once inconsistent, it means a huge troubleshooting cost.

In response to the pain points of Vite, Farm uses Rust to re-implement the compile capability of CSS/TS/JS/Sass , which can achieve millisecond-level project launch. For most cases, it can control the HMR time within 10ms.

# Turbopack

img

Compared to Farm, Turbopack is more trustworthy and has received more attention due to the support of next.js.

img

Turbopack is also a front-end project building tool based on Rust. Turbopack is built on a new incremental architecture, and only focuses on the minimum resources required for development when packaging, so whether it is startup speed or HMR speed, it has far better performance than Vite.

On an application with 3000 modules, Turbopack only takes 1.8 seconds, while Vite takes 11.4 seconds.

img

Turbopack is provided by the Vercel team, focusing on improving the speed of Next.js packaging tool. And the future goal is to replace webpack and become the new generation of front-end packaging tool. Therefore, the maturity and popularity of Next.js will also drive Turbopack to become a more reliable packaging tool.

# Rspack

img

Rspack is a project packaging tool provided by the Byte team. Like Turbopack, it fully utilizes the performance advantages of the Rust language and has significantly improved packaging speed.

However, unlike Turbopack, Rspack has chosen a route that prioritizes compatibility with the webpack ecosystem. On the one hand, these compatibility may bring certain performance overhead, but in actual business implementation, this performance overhead is acceptable. On the other hand, these compatibility also enable Rspack to better integrate with upper-level frameworks and ecosystems, enabling gradual business migration.

Currently, the development team of Rspack is also actively recruiting. Obviously, they have a very clear plan for future development.

img

# Vite is refactoring with rust

Vite, as a new generation of high-performance packaging tool, really amazed everyone when it first appeared. But it couldn’t resist the various crazy roll kings using Rust to overtake. Instead, Vite became the background board, being pressed on the ground and rubbed crazily. Therefore, in order not to be suppressed too much in performance, the Vite team is developing various alternative solutions based on Rust to solve Vite’s current pain points.

Rolldown

img

The Vite team is developing Rolldown and has open-sourced it. It is an alternative to Rollup developed using Rust. Its focus will be on local-level performance while maintaining compatibility with Rollup. The ultimate goal is to quietly switch to Rolldown in Vite with minimal impact on Vite users.

However, at present, there is a lot of pressure for Vite to achieve the goal of rust refactoring. Therefore, the Vite team has planned four stages to promote this

\1. Replace esbuild 2. Replace Rollup 3. Use Rust to achieve built-in conversion of common requirements, such as compile ts , JSX, etc 4. Refactor Vite completely with Rust

# Leptos

img

Leptos is a Rust-based React/Solid framework. It also implements fine grain-level reactive updates based on signal.

The basic grammar is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
#[component]
fn App() -> impl IntoView {
let (count, set_count) = create_signal(0); view! {
<button
on:click=move |_| set_count.update(|n| *n += 1)
>
"click me"
</button> <p>
<strong>"Reactive"</strong>
{count}
</p>
}
}

It is very similar to Solid in terms of grammar. However, in terms of grammar details, it is designed more reasonably than Solid. It has more intuitive thinking in semantics. This means that Leptos does a better job of compiling based on rust.

1
2
3
4
5
6
7
8
9
10
11
#[component]
fn ProgressBar(
#[prop(default = 100)]
max: u16,
#[prop(into)]
progress: Signal<i32>
) -> impl IntoView {
view! {
<progress max=max value=progress />
}
}

Although Leptos is designed to be advanced and has strong performance, it is based on Rust and has a very high cost to get started, so it may encounter a lot of difficulties in promotion. However, this still cannot stop the enthusiasm of many programmers for it.

I am also one of the developers who really like Leptos, and I regard it as one of the main projects to familiarize myself with Rust syntax learning. Because this is a field that we front-end developers are more familiar with, mastering Rust through it can achieve twice the result with half the effort.

Of course, there is still a lot of potential in the tool that I have not fully explored, such as the official documentation claiming to be a full Stack framework, but because I have not yet digested it, I need to further learn to understand it.

# dioxus

img

Dioxus is a more ambitious cross-platform client development framework, and at the same time, it can achieve full stack development. It has some similarities with Leptos in implementation principles and syntax design, but it is completely different in UI syntax performance

A simple example can be seen

1
2
3
4
5
6
7
fn app() -> Element {
let mut count = use_signal(|| 0); rsx! {
h1 { "High-Five counter: {count}" }
button { onclick: move |_| count += 1, "Up high!" }
button { onclick: move |_| count -= 1, "Down low!" }
}
}

From this grammar design, it can be seen that it aims to unify the world. It attempts to cover all scenarios such as web development, mobile end app development, and desktop app development.

img

The simple and practical feeling is that the framework has the suspicion of over-imitating React, so that I, who is familiar with React, can learn it more easily than Leptos.

# Tauri

img

Tauri is an alternative to Electron.

Electron has two main pain points, one is that the package size is too large, and the other is that memory consumption is severe. Therefore, its alternative solutions are endless. Unlike the several Rust frameworks introduced earlier, Tauri’s development has become mature and has been applied in many commercial projects.

Most importantly, I have started to let my students learn it and use it as a core project highlight to cope with the increasingly competitive interview scene. And the effect is not bad. Judging from the interview results in the past six months, many domestic companies have begun to pay attention to the benefits brought by Tauri.

Due to Rust abandoning the huge size of Chromiun and Node.js, for the same project, the packaging size can be reduced from 60M in Electron to 4M, and memory consumption can also be reduced from 500M to around 150M.

# Servo

img

This is a browser project based on Rust development and aimed at replacing Chrome. The project was an experimental project developed by Mozilla in the early days. Due to limited funds, it was put on hold for a long time. Now, with Rust becoming popular, it is ready to step up its efforts and the recent version iteration is very fast. At this time, Servo has been taken over by the Linux Foundation.

Servo attempts to create a large-scale parallel computing page rendering mode to accelerate rendering, layout, HTML parsing, image decoding, etc. Tests on the Arm architecture show that Servo’s performance is significantly better than Chromium.

Then I downloaded this browser to play with it, but found out that it was still a rudimentary version. Basic UI functions had not been developed yet, and many page layouts still had problems with disorder.

It can only be said that it is temporarily worth paying attention to and has great development potential. If used, it may still be early.

# Deno

img

Deno is a JavaScript runtime built on Rust. It comes from the same boss as Node.js. The latest version of Deno is also developed on Rust.

Personally, the biggest charm of Deno lies in its direct native support for TypeScript and support for JSX/TSX. Therefore, I am very optimistic about the future development of Deno, which is getting better and better, although the current ecosystem is not yet sufficient to compete with Node.

# Summary

It is obvious that Rust is invading every aspect of the front-end. Although it is not mature enough in some aspects, it has shown potential, and in some aspects, it has already established clear advantages.

I think front-end development can no longer ignore the existence of Rust . Due to its ultra-high performance and security, Rust has been highly recognized in various fields such as “operating system level, AI, game development, server level, Inter-App communications solutions, high-performance web applications…” The community has a very high active level and the ecological development is very rapid.

Therefore, from the end of last year until now, I have been immersed in learning Rust. Overall, I feel that learning Rust from the perspective of front-end development is relatively easy. It takes about a day to learn all the basic syntax, but we need to have a very accurate understanding of memory. If you are confused about memory, it may be difficult to learn Rust.

Then we need to spend more time learning the development mindset and ecosystem of Rust. For front-end development, Leptos is a good learning and practice project.

13 Interesting Python Scripts

13 Interesting Python Scripts

Every day we face many programming challenges that require advanced coding. You can’t solve these problems with simple basic Python syntax. In this article, I will share 13 advanced Python scripts that can become easy-to-use tools in your project. If you don’t currently use these scripts, you can add them to your favorites for retention.

# Make web robots

This script will help you automate websites using Python. You can build a web robot that can control any website. Check out the code below. This script is very convenient in web crawling and web automation.

1
2
3
4
5
6
7
8
9
10
11
# pip install selenium
import time
from selenium import webdriver
from selenium.webdriver.common.keys
import Keysbot = webdriver.Chrome("chromedriver.exe")
bot.get('http://www.google.com')
search = bot.find_element_by_name('q')
search.send_keys("@codedev101")
search.send_keys(Keys.RETURN)
time.sleep(5)
bot.quit()

# Python Image Enhancement

Enhance your photos with the Python Pillow library to make them look better. In the code below, I’ve implemented four ways to enhance any photo.

1
2
3
4
5
6
7
8
9
10
11
# pip install pillow
from PIL import Image,ImageFilter
from PIL import ImageEnhance
im = Image.open('img.jpg')
# Choose your filter
# add Hastag at start if you don't want to any filter below
en = ImageEnhance.Color(im)
en = ImageEnhance.Contrast(im)
en = ImageEnhance.Brightness(im)
en = ImageEnhance.Sharpness(im)# result
en.enhance(1.5).show("enhanced")

# Get song lyrics

This advanced script will show you how to get lyrics from any song. First, you must get a free API key from the Lyricsgenius website, and then, you must follow the following code. This advanced script will show you how to get lyrics from any song. First, you must get a free API key from the Lyricsgenius website, and then, you must follow the following code.

1
2
3
4
5
6
7
8
# pip install lyricsgenius
import lyricsgenius
api_key = "xxxxxxxxxxxxxxxxxxxxx"
genius = lyricsgenius.Genius(api_key)
artist = genius.search_artist("Pop Smoke",
max_songs=5,sort="title")
song = artist.song("100k On a Coupe")
print(song.lyrics)

# Get Exif data for photos

Use the Python Pillow module to get the Exif data of any photo. Check out the code mentioned below. I provide two methods to extract the Exif data of photos.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Get Exif of Photo
# Method 1
# pip install pillow
import PIL.Image
import PIL.ExifTags
img = PIL.Image.open("Img.jpg")
exif_data =
{
PIL.ExifTags.TAGS[i]: j
for i, j in img._getexif().items()
if i in PIL.ExifTags.TAGS
}
print(exif_data)
# Method 2
# pip install ExifRead
import exifread
filename = open(path_name, 'rb')
tags = exifread.process_file(filename)
print(tags)

# Search on google

You can extract Retargeting URL from Google search engine , install the following mention module and follow the code.

1
2
3
4
5
# pip install google
from googlesearch import search
query = "Medium.com"
for url in search(query):
print(url)

# Conversion: hexadecimal to RGB

The script will simply convert Hex to RGB . Check out the sample code below.

1
2
3
4
5
6
# Conversion: Hex to RGB
def Hex_to_Rgb(hex):
h = hex.lstrip('#')
return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
print(Hex_to_Rgb('#c96d9d')) # (201, 109, 157)
print(Hex_to_Rgb('#fa0515')) # (250, 5, 21)

# Convert photos to Cartonize

This simple advanced script will convert your photos to Cartonize format. Check out the sample code below and give it a try.

1
2
3
4
5
6
7
8
9
10
# pip install opencv-python
import cv2
img = cv2.imread('img.jpg')
grayimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
grayimg = cv2.medianBlur(grayimg, 5)
edges = cv2.Laplacian(grayimg , cv2.CV_8U, ksize=5)
r,mask =cv2.threshold(edges,100,255,cv2.THRESH_BINARY_INV)
img2 = cv2.bitwise_and(img, img, mask=mask)
img2 = cv2.medianBlur(img2, 5)
cv2.imwrite("cartooned.jpg", mask)

# Speed Testing with Python

This advanced script helps you test your internet speed using Python. Just install the speed test module and run the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# pip install pyspeedtest
# pip install speedtest
# pip install speedtest-cli
#method 1
import speedtest
speedTest = speedtest.Speedtest()
print(speedTest.get_best_server())
#Check download speed
print(speedTest.download())
#Check upload speed
print(speedTest.upload())
# Method 2
import pyspeedtest
st = pyspeedtest.SpeedTest()
st.ping()
st.download()
st.upload()

# Site Status

You can use Python to check if the website is running normally. Check the following code, it displays 200, which means the website is launched. If it displays 404, it means the website is closed.

1
2
3
4
5
6
7
8
9
10
# pip install requests
#method 1
import urllib.request
from urllib.request import Request, urlopenreq = Request('https://medium.com/@pythonians', headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).getcode()
print(webpage) # 200
# method 2
import requests
r = requests.get("https://medium.com/@pythonians")
print(r.status_code) # 200

# Extract OCR text from images

OCR is a method of recognizing text from numbers and scanned docs. Many developers use it to read handwritten data, and the following Python code can convert scanned images to OCR text format.

Note: You must download tesseract.exe from Github .

1
2
3
4
5
6
7
# pip install pytesseract
import pytesseract
from PIL import Image
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
t=Image.open("img.png")
text = pytesseract.image_to_string(t, config='')
print(text)

# Get Windows version

This simple script will help you get the full version of the window you are currently using.

1
2
3
4
5
# Window Versionimport wmi
data = wmi.WMI()
for os_name in data.Win32_OperatingSystem():
print(os_name.Caption)
# Microsoft Windows 11 Home

# Convert PDF to Image

Use the following code to convert all Pdf pages into images.

1
2
3
4
5
6
7
# PDF to Images
import fitz
pdf = 'sample_pdf.pdf'
doc = fitz.open(pdf)
for page in doc:
pix = page.getPixmap(alpha=False)
pix.writePNG('page-%i.png' % page.number)

# Empty Recycling Bin

This simple script allows you to empty your Recycle Bin with Python. Check out the code below to learn how.

1
2
3
4
5
6
7
# pip install winshell
import winshell
try:
winshell.recycle_bin().empty(confirm=False, /show_progress=False, sound=True)
print("Recycle bin is emptied Now")
except:
print("Recycle bin already empty")
Go 1.22 Unveiled: Embrace Simplicity with New Slice Features and Enhanced Functions!

Go 1.22 Unveiled: Embrace Simplicity with New Slice Features and Enhanced Functions!

Starting from the new version Go 1.22, there have been some additions and changes to the behavior of slices, making them more developer-friendly.

The following provides an explanation and overview of the adjustments made to functions such as Concat, Delete, DeleteFunc, Replace, Compact, CompactFunc, Insert, etc.

# New Addition: Concat Function

In previous Go versions, when concatenating two slices, developers often had to manually write code like the following:

1
2
3
4
5
6
7
func main() {
s1 := []string{"A", "B", "C"}
s2 := []string{"Deep-A", "Water fish", "A"}

s3 := append(s1, s2...)
fmt.Println(s3)
}

Output:

1
[A B C Deep-A Water fish A]

If such concatenation is frequently used in a Go project, developers might create a utility function, similar to the following:

1
2
3
4
5
6
7
8
9
func concatSlice[T any](first []T, second []T) []T {
n := len(first)
return append(first[:n:n], second...)
}
func main() {
s1 := []string{"A", "Deep-A"}
s2 := []string{"Water fish", "C", "A"}
s3 := concatSlice(s1, s2) fmt.Println(s3)
}

Output:

1
[A Deep-A Water fish C A]

If there’s a need to merge more than two slices, the implementation of this function becomes more complex.

However!

Starting from Go 1.22, a new Concat function has been introduced, making it easier to concatenate (join) multiple slices without the need to maintain a custom method.

The signature of the Concat function is as follows:

1
func Concat[S ~[]E, E any](slices ...S) S

Usage example:

1
2
3
4
5
6
7
8
9
10
11
import (
"fmt"
"slices"
)
func main() {
s1 := []string{"A"}
s2 := []string{"Deep-A", "Blue fish", "B"}
s3 := []string{"Lucky fish", "A"}
resp := slices.Concat(s1, s2, s3)
fmt.Println(resp)
}

This function is implemented based on generics, eliminating the need to implement it internally for each data type. It provides a convenient way for users, but it’s essential to ensure that the input slice types are consistent.

The internal implementation of the function is relatively straightforward, as shown in the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Concat returns a new slice concatenating the passed in slices.
func Concat[S ~[]E, E any](slices ...S) S {
size := 0
for _, s := range slices {
size += len(s)
if size < 0 {
panic("len out of range")
}
}
newslice := Grow[S](nil, size)
for _, s := range slices {
newslice = append(newslice, s...)
}
return newslice
}

It’s worth noting that a panic is triggered when size < 0 , but this seems to be more of a defensive programming measure. In general scenarios, this should not be triggered.

# Changes in Behavior for Delete and Related Functions

Starting from Go 1.22, the behavior of functions related to slices that reduce the slice segment/size has been adjusted. After the slice has been reduced, elements between the new length and the old length will be set to zero values.

This adjustment affects functions like Delete, DeleteFunc, Replace, Compact, CompactFunc, etc.

Here are some specific examples, divided into the old version (Go 1.21) and the new version (Go 1.22 and later).

# Delete-related Functions

Old version:

1
2
3
4
5
6
func main() {
s1 := []int{11, 12, 13, 14}
s2 := slices.Delete(s1, 1, 3)
fmt.Println("s1:", s1)
fmt.Println("s2:", s2)
}

Output:

1
2
s1: [11 14 13 14]
s2: [11 14]

In the new version, the program remains unchanged, but the output result has changed:

1
2
s1: [11 14 0 0]
s2: [11 14]

# Compact Function

Old version:

1
2
3
4
5
6
func main() {
s1 := []int{11, 12, 12, 12, 15}
s2 := slices.Compact(s1)
fmt.Println("s1:", s1)
fmt.Println("s2:", s2)
}

Output:

1
2
s1: [11 12 15 12 15]
s2: [11 12 15]

In the new version, the program remains unchanged, but the output result has changed:

1
2
s1: [11 12 15 0 0]
s2: [11 12 15]

# Replace Function

Old version:

1
2
3
4
5
6
func main() {
s1 := []int{11, 12, 13, 14}
s2 := slices.Replace(s1, 1, 3, 99)
fmt.Println("s1:", s1)
fmt.Println("s2:", s2)
}

Output:

1
2
s1: [11 99 14 14]
s2: [11 99 14]

In the new version, the program remains unchanged, but the output result has changed:

1
2
s1: [11 99 14 0]
s2: [11 99 14]

# Changes in Behavior for Insert Function, May Cause Panic

Old version:

1
2
3
4
5
6
func main() {
s1 := []string{"A", "Deep-A", "Water fish"}
s2 := slices.Insert(s1, 4)
fmt.Println("s1:", s1)
fmt.Println("s2:", s2)
}

Output:

1
2
s1: [A Deep-A Water fish]
s2: [A Deep-A Water fish]

In the new version, the program remains unchanged, but the output result has changed:

1
2
3
4
5
panic: runtime error: slice bounds out of range [4:3]

goroutine 1 [running]:
slices.Insert[...](0xc00010e0c0, 0x10100000010, 0x7ecd5be280a8)
...

In the above scenario, when using the slices.Insert function and not filling in a specific element to insert, it would run normally in the old version but would cause a panic in the new version.

Of course, if an element is filled in from the beginning, it would cause a panic in both the new and old versions. It can be considered as fixing a boundary value issue.

March 2024 Programming Language Ranking, the gap between Python and other languages has never been so big!

March 2024 Programming Language Ranking, the gap between Python and other languages has never been so big!

# March 2024 Programming Language Ranking, the gap between Python and other languages has never been so big!

TIOBE’s March 2024 programming language rankings have been released, and the official title is: The gap between Python and the rest has never been that large.

The TIOBE index showed a relatively calm trend in February, but there were also some notable changes. According to TIOBE CEO Paul Jansen, the most noteworthy is that Python currently leads other language vendors by 4.5%, while Scratch returns to the top ten.

img

Meanwhile, Rust continues its upward trend.

img

Python, as a high-level programming language, has a wide range of applications and diverse advantages in today’s software development and data science fields.

Advantages of Python:

  • Easy to learn: Python syntax is concise and clear, similar to natural language, making it easy to learn and understand. This makes Python the preferred language for beginners, non-computer professionals, and education professionals.
  • Diverse Application Areas: Python can be used in various fields, including web development, data science, artificial intelligence, Machine Learning, scientific computing, natural language processing, network programming, etc. Its flexibility and versatility make Python a versatile programming language.
  • Python has a large and active community and ecosystem, supported by rich third-party libraries and tools such as NumPy, Pandas, TensorFlow, PyTorch, etc. These libraries can greatly simplify the development process and improve efficiency.
  • ** Cross-platform: ** Python is a cross-platform language that can run on a variety of operating systems, including Windows, Linux, macOS, etc., which makes it easy for developers to deploy their applications in different environments.
  • Rapid development: Python has the characteristics of rapid development and iteration. By using features such as dynamic typing and automatic memory management, prototypes can be quickly built and iterative development can be carried out.
  • ** Community support and rich documentation: ** Python has a large developer community with rich documentation, tutorials, and Q & A websites, such as Python official documentation, Stack Overflow, etc. Developers can easily obtain the help and resources they need.
  • ** Extensive tool support: ** Python not only supports a variety of Integrated Development Environments (IDEs), such as PyCharm, Jupyter Notebook, etc., but also supports a variety of text editors, such as Sublime Text, VS Code, etc. Developers can choose the appropriate tool according to their preferences for development.

In terms of application scope, Python is almost ubiquitous.

  • Web Development: Python excels in building web applications through frameworks such as Django and Flask.
  • Data science and artificial intelligence: Python has a wide range of applications in the fields of Data Analysis, data lake visualization, Machine Learning, and artificial intelligence. Libraries such as Pandas, NumPy, Scikit-learn, and Matplotlib support the development of these fields.
  • ** Scientific Computing: ** Python is also widely used in the fields of scientific computing and engineering. Libraries such as SciPy and SymPy provide rich scientific computing functions.
  • Python has strong capabilities in processing text data and natural language processing. Libraries such as NLTK and spaCy provide developers with rich tools and algorithms.

img

Python language version history:

img

Support time for each version:

img

Python official website: https://www.python.org/

Python Beginner Tutorial: https://www.runoob.com/python3/python3-tutorial.html

Long press the following QR code to access the Python beginner’s tutorial:

img

Python historical ranking change chart:

img

This month, the top ten rankings are:

# Python,C,C++,Java,C#,JavaScript,SQL,Go,Scratch,Visual Basic。

img

# Python, C, C++, Java, C #, JavaScript, SQL, Go, Scratch, Visual Basic historical change graph:

img

Ranked 11–20 programming languages, *PHP has fallen out of the top 10* :

img

Programming languages ranked 21–50:

img

51–100 programming languages:

ABAP, ABC, ActionScript, Algol, Apex, APL, Awk, bc, Bourne shell, Carbon, CFML, CHILL, CLIPS, Clojure, Crystal, Curl, DiBOL, Eiffel, Elixir, Groovy, Hack, Icon, IDL, Io, J, J#, JScript, LabVIEW, Ladder Logic, LiveCode, Modula-2, NATURAL, Nim, OCaml, OpenCL, OpenEdge ABL, PL/I, PL/SQL, PostScript, Q, Racket, REXX, Ring, Smalltalk, SPARK, SPSS, Tcl, VHDL, Wolfram, Zig

Historical rankings of major programming languages (1988–2024):

img

Programming Language “Celebrity List” (2003–2023):

img

TIOBE publishes a monthly ranking of programming languages based on the number of global technical engineers, courses, and third-party suppliers, including popular search engines and technical communities such as Google, Baidu, Wikipedia, Lingo, etc.

The data reflects the changing trend of mainstream programming languages, which can serve as a reference for our learning and work. However, each language has its own suitable application scenarios, so there is no need to pay too much attention to it. After all, the quality of a language depends on how it is used.

The following video shows the changing trends of programming languages in recent decades.

Reference: https://www.tiobe.com/tiobe-index/

Useful and Versatile Go Code Snippets

Useful and Versatile Go Code Snippets

During the development of production projects, I often find myself repeating code and unconsciously using certain techniques until I realize them later during a retrospective.

To address this issue, I developed a solution that has been very helpful for me, and I believe it might be useful for others as well.

Here are some useful and versatile code snippets randomly selected from my utility library, without specific categorization or system-specific techniques.

# 1. Timing Execution

If you want to track the execution time of a function in Go, there’s a simple and efficient technique with just one line of code, using the defer keyword. You only need a TrackTime function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Utility
func TrackTime(pre time.Time) time.Duration {
elapsed := time.Since(pre)
fmt.Println("elapsed:", elapsed)

return elapsed
}

func TestTrackTime(t *testing.T) {
defer TrackTime(time.Now()) // <--- THIS

time.Sleep(500 * time.Millisecond)
}

// Output:
// elapsed: 501.11125ms

# 1.5. Two-Stage Deferred Execution

Go’s defer is not only for cleanup tasks but can also be used for preparation tasks. Consider the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func setupTeardown() func() {
fmt.Println("Run initialization")
return func() {
fmt.Println("Run cleanup")
}
}

func main() {
defer setupTeardown()() // <--------
fmt.Println("Main function called")
}

// Output:
// Run initialization
// Main function called
// Run cleanup

The beauty of this pattern is that with just one line of code, you can accomplish tasks like:

  • Opening a database connection and then closing it.
  • Setting up a mock environment and then tearing it down.
  • Acquiring a distributed lock and then releasing it.

“Well, that seems clever, but how practical is it in real-world scenarios?”

Remember the timing execution technique? We can do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
func TrackTime() func() {
pre := time.Now()
return func() {
elapsed := time.Since(pre)
fmt.Println("elapsed:", elapsed)
}
}

func main() {
defer TrackTime()()

time.Sleep(500 * time.Millisecond)
}

Note! What if there’s an error when I connect to the database?

Indeed, patterns like defer TrackTime() or defer ConnectDB() might not handle errors properly. This technique is most suitable for testing or when you are willing to take the risk of fatal errors, as shown in the following test-oriented approach:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func TestSomething(t *testing.T) {
defer handleDBConnection(t)()
// ...
}

func handleDBConnection(t *testing.T) func() {
conn, err := connectDB()
if err != nil {
t.Fatal(err)
}

return func() {
fmt.Println("Closing connection", conn)
}
}

This way, database connection errors can be handled during testing.

# 2. Pre-allocate Slices

According to insights from the article “Performance Improvements in Go,” pre-allocating slices or maps can significantly improve the performance of a Go program. However, it’s worth noting that if we are not careful and use append instead of indexing (like a[i] ), this approach may sometimes lead to errors. Did you know that we can use a pre-allocated slice without specifying the array length (zero) as explained in the mentioned article? This allows us to use the pre-allocated slice just like using append :

1
2
3
4
5
6
7
// Instead of
a := make([]int, 10)
a[0] = 1

// Use it like this
b := make([]int, 0, 10)
b = append(b, 1)

# 3. Method Chaining

Method chaining technique can be applied to function (pointer) receivers. To illustrate this, let’s consider a Person struct with two functions AddAge and Rename for modifications:

1
2
3
4
5
6
7
8
9
10
11
12
type Person struct {
Name string
Age int
}

func (p *Person) AddAge() {
p.Age++
}

func (p *Person) Rename(name string) {
p.Name = name
}

If you want to add age to a person and then rename them, the conventional way is:

1
2
3
4
5
6
func main() {
p := Person{Name: "Aiden", Age: 30}

p.AddAge()
p.Rename("Aiden 2")
}

Alternatively, we can modify the AddAge and Rename functions’ receivers to return the modified object itself, even though they typically don’t return anything:

1
2
3
4
5
6
7
8
9
func (p *Person) AddAge() *Person {
p.Age++
return p
}

func (p *Person) Rename(name string) *Person {
p.Name = name
return p
}

By returning the modified object itself, we can easily chain multiple function receivers together without adding unnecessary lines of code:

1
p = p.AddAge().Rename("Aiden 2")

# 4. Go 1.20 Allows Slicing into an Array or Array Pointer

When we need to convert a slice to a fixed-size array, direct assignment is not possible, for example:

1
2
3
4
a := []int{0, 1, 2, 3, 4, 5}
var b [3]int = a[0:3]

// Cannot assign a[0:3] (type []int) to a variable of type [3]int (incompatible assignment)

With the introduction of this feature in Go 1.17, and with the release of Go 1.20, the conversion process becomes simpler with more convenient literals:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Go 1.20
func Test(t *testing.T) {
a := []int{0, 1, 2, 3, 4, 5}
b := [3]int(a[0:3])

fmt.Println(b) // [0 1 2]
}

// Go 1.17
func TestM2e(t *testing.T) {
a := []int{0, 1, 2, 3, 4, 5}
b := *(*

[3]int)(a[0:3])

fmt.Println(b) // [0 1 2]
}

Just a quick reminder: you can use a[:3] instead of a[0:3] . I mention this for clarity.

# 5. Package Initialization with “import _”

Sometimes, in a library, you might come across import statements combining an underscore (_) like this:

1
2
3
import (
_ "google.golang.org/genproto/googleapis/api/annotations"
)

This executes the package’s initialization code (init function) without needing to create a named reference to it. This allows you to initialize packages, register connections, and perform other tasks before running the code.

Let’s better understand how it works with an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Underscore
package underscore

func init() {
fmt.Println("init called from underscore package")
}
// Main
package main

import (
"fmt"
_ "lab/underscore"
)

func main() {}
// Output: init called from underscore package

# 6. Importing with “import .”

After understanding how to import with an underscore, let’s see how more commonly used is the dot (.) operator.

As a developer, the dot (.) operator can be used to import exported identifiers from an imported package without specifying the package name. This is a useful shortcut for lazy developers, especially when dealing with long package names in a project, like externalmodel or doingsomethinglonglib .

To demonstrate, here’s a simple example:

1
2
3
4
5
6
7
8
9
10
11
package main

import (
"fmt"
. "math"
)

func main() {
fmt.Println(Pi) // 3.141592653589793
fmt.Println(Sin(Pi/2)) // 1
}

# 7. Go 1.20 Allows Merging Multiple Errors into a Single Error

Go 1.20 introduces new features to the errors package, including support for multiple errors and changes to errors.Is and errors.As . One of the new functions added in errors is Join , which we’ll discuss in detail below:

1
2
3
4
5
6
7
8
9
10
11
12
var (
err1 = errors.New("Error 1st")
err2 = errors.New("Error 2nd")
)

func main() {
err := err1
err = errors.Join(err, err2)

fmt.Println(errors.Is(err, err1)) // true
fmt.Println(errors.Is(err, err2)) // true
}

If there are multiple tasks causing errors, you can use the Join function instead of manually managing arrays. This simplifies the error handling process.

# 8. Checking if an Interface Is Truly Nil

Even if an interface holds a value of nil , it doesn’t mean the interface itself is nil . This can lead to unexpected errors in a Go program. Therefore, it’s important to know how to check if an interface is truly nil .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func main() {
var x interface{}
var y *int = nil
x = y

if x != nil {
fmt.Println("x != nil") // <-- Actual output
} else {
fmt.Println("x == nil")
}

fmt.Println(x)
}

// Output:
// x != nil
// <nil>

How do we determine if the interface{} value is nil ? Fortunately, there’s a simple tool to help us with that:

1
2
3
4
5
6
7
func IsNil(x interface{}) bool {
if x == nil {
return true
}

return reflect.ValueOf(x).IsNil()
}

# 9. Parsing time.Duration in JSON

When parsing JSON, using time.Duration can be a cumbersome process because it requires adding 9 zeros (i.e., 1000000000) after the second. To simplify this process, I created a new type called Duration :

1
type Duration time.Duration

To parse strings (like “1s” or “20h5m”) into an int64 type duration, I also implemented custom parsing logic for this new type:

1
2
3
4
5
6
7
8
9
10
11
12
func (d *Duration) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
dur, err := time.ParseDuration(s)
if err != nil {
return err
}
*d = Duration(dur)
return nil
}

However, it’s worth noting that the variable ‘d’ should not be nil, or it might result in marshaling errors. Alternatively, you can also check ‘d’ at the beginning of the function.

Will be the 10 best Python GUI frameworks in 2024

Will be the 10 best Python GUI frameworks in 2024

# Will be the 10 best Python GUI frameworks in 2024

** Hello 🖖, I am a newsletter! A wild programmer. ** Love programming, but the current job has nothing to do with programming.

Currently trying various side jobs, currently doing:

The editor uses Neovim more. If you also like to use Nvim, we can communicate together.

My Nvim configuration: https://github.com/alpha87/nvim.

My personal official account often shares articles related to programming, as well as some side projects that I have already operated and can actually get started with. Welcome to follow!

A graphical User Interface (commonly referred to as a GUI) is the interactive environment that users encounter when opening an application or website. As an interactive visual component system of computer software, a graphical User Interface displays objects that convey information and represent user actions. These objects can dynamically change properties such as color, size, or visibility based on user interaction behavior. Icons, cursors, buttons, and other graphical elements (usually enhanced by visual effects such as sound or transparency) contribute to the entire graphical User Interface.

The quality of the graphical User Interface has a significant impact on the reputation and user base of the platform. The combination of these interactive elements plays a crucial role in shaping the User Experience of an application or website.

img

# 1. PyQt5

PyQt5 is developed by Riverbank Computing and is a popular Python framework for graphical User Interface (GUI). The framework is based on the Qt framework, which is a universal cross-platform tool widely used to create applications for various platforms.

PyQt5 has full cross-platform compatibility, allowing developers to seamlessly build applications on Mac, Windows, Linux, iOS and Android. The addition of QtGUI and QtDesigner modules makes it easy for users to integrate visual elements through a friendly drag-and-drop interface. In addition, developers can choose to manually code these elements, making it flexible to develop applications of all sizes, from small to large.

img

You can install PyQt5 using the pip command.

1
pip install PyQt5

# 2. Tkinter

Tkinter is a well-known Python library for creating graphical User Interfaces (GUIs). This open-source library is known for its simplicity and is easily pre-installed in Python without additional installation work. Its user-friendliness makes it an excellent choice for beginners and intermediate programmers. However, it is worth noting that Tkinter may not be suitable for handling large projects. In plain language, it is okay to practice, but if you really want to do something, forget it.

img

In Tkinter, visual components are called widgets, and each component provides varying degrees of customization. The library provides various commonly used elements that developers may already be familiar with, including frameworks, buttons, check buttons, labels, file dialog boxes, and canvas.

Tkinter is already included in most Python installers, so it usually doesn’t need to be installed separately.

# 3. wxPython

WxPython is another well-known Python library for GUI development, which provides Python developers with the ability to seamlessly build native User Interfaces without adding any additional overhead to the application. Similar to other libraries and frameworks, wxPython is compatible with various platforms, including Mac OS, Windows, Linux, and Unix-based systems.

img

One of the main features of wxPython is its extensive collection of small tools, which is a major advantage. In addition, the appearance of wxPython is attractive on all platforms and does not require a lot of custom modifications. However, it should be noted that compared with other frameworks such as Tkinter, the learning curve of wxPython is relatively steep.

You can use the pip command to install wxPython.

1
pip install wxpython

# 4. PySimpleGUI

PySimpleGUI was launched in 2018 and is designed to simplify GUI development for Python beginners. Many alternative frameworks involve more complex programs, but PySimpleGUI allows users to immediately get involved without having to deal with complex details related to other libraries.

PySimpleGUI utilizes four low-level graphical User Interface frameworks: Qt, Tkinter, wxPython, and Remi. By abstracting most of the low-level code, it greatly reduces the complexity of user usage. This method allows beginners to choose their favorite graphical User Interface framework and effortlessly access relevant visual elements, enabling them to easily create intuitive User Interfaces.

img

You can install PySimpleGUI using the pip command.

1
pip install PySimpleGUI

# 5. Libavg

Libavg is a graphical User Interface framework that uses Python as a scripting language. Hardware accelerated with OpenGL and GPU shaders, it is one of the top libraries for User Interfaces tailored for modern touch devices. This Python library has various features, including camera support, animation capabilities, text alignment, GPU effects, and more. Its advanced screen layout engine includes techniques for rotating, scaling, Blend Mode, cropping, and various other operations on visual elements. Libavg is written in C++ and executes extremely quickly, thereby improving overall performance.

img

Libavg requires additional dependencies and build steps. For installation instructions, please refer to the official documentation, which will not be explained in detail here.

# 6. PyForms

PyForms GUI framework is Python’s interpretation of Windows Forms, providing developers with the ability to design highly interactive interfaces in Windows GUI mode, web mode, and end point mode. This open-source cross-platform library simplifies the process of developing applications for various platforms with minimal code modifications. In addition, PyForms also integrates popular graphical center library instances such as PyQT and OpenGL.

The PyForms structure is divided into three different parts: PyForms-GUI, PyForms-Web, and PyForms-end point. Each layer is helpful for executing PyForms applications in Windows, Web, or end point environments.

img

You can install pyforms using the pip command.

1
pip install pyforms

# 7.Kivy

Kivy is an acceleration framework supported by OpenGL ES 2, designed for creating innovative User Interfaces. It supports multiple platforms and is suitable for Windows, Mac, Linux, Android, and iOS. The toolkit of this open-source library includes more than 20 small tools and is a comprehensive resource library. Developed using a combination of Python and Cython, Kivy excels in creating intuitive User Interfaces, especially multi-touch applications. It helps to achieve natural User Interfaces (NUI), allowing users to effortlessly master various interactions that are usually hidden.

Kivy enables interface designers to code and deploy across platforms, and its built-in support for OpenGL ES 2 ensures the integration of modern graphics and technology.

img

You can install Kivy using the pip command.

1
pip install kivy

# 8.PySide2

PySide2, also known as QT for Python, is a well-known Python GUI library that provides official Python bindings for Qt. These bindings allow integration of Qt’s APIs into Python applications, while the binding generator tool facilitates C++ projects’ engagement with Python.

Qt is recognized as the gold standard for graphical User Interface design and the benchmark for evaluating other Python graphical User Interface frameworks. With PySide2, Python developers can use a powerful set of tools and libraries to quickly and flexibly create User Interfaces.

img

You can install PySide2 using the pip command.

1
pip install PySide2

# 9.Wax

Wax is the wrapper of wxPython, which is the last part of our compile work. In addition to providing similar functionality to wxPython, Wax stands out with its particularly user-friendly User Interface. As an extension module of Python, Wax provides convenience for the development of cross-platform applications.

Wax is based on the efficient wxWindows platform, with the specific goal of simplifying GUI development for accessing Python elements and objects. This design choice ensures that Wax achieves commendable levels of efficiency and speed.

You can install Wax using the pip command.

1
pip install wax

# 10.PyGUI

PyGUI is a simple and clear Application Programming Interface that enables developers to build User Interfaces with native elements for Python applications. This lightweight framework minimizes the code required between the application and the target platform, thereby improving overall efficiency.

PyGUI provides convenience for developing applications on various systems, including Windows machines, MacOS devices, and Unix-based systems. It is worth noting that the documentation for this library is written in Python, so there is no need to refer to other graphical User Interface libraries.

img

You can install PyGUI using the pip command.

1
pip install pygui

Python provides a rich library for developing graphical User Interfaces (GUIs), each with unique advantages and limitations. For beginners, Tkinter is known for its simplicity and user-friendly features, making it a great starting point. Meanwhile, PyQt5 and PySide2 offer advanced features and extensive customization options. Kivy provides convenience for cross-platform application development, while wxPython ensures a native look and feel on Windows, macOS, and Linux.

Python’s various graphical User Interface libraries provide developers with basic tools for designing visually appealing and interactive applications. Choosing the right library can simplify the development process and create high-quality software that meets user expectations.

What happened when Fortran entered the top 10 programming language rankings in May 2024?

What happened when Fortran entered the top 10 programming language rankings in May 2024?

TIOBE’s programming language rankings for May 2024 have been released. The official title is: Fortran in the top 10, what is going on?

Fortran, a veteran language in the programming world, has once again entered the Top 10 list of programming languages after more than 20 years of silence.

This makes people curious, what made this “old guy” radiate a second spring?

img

Since its birth in 1957, Fortran has never stopped innovating itself. The latest ISO Fortran 2023 standard is proof of its continuous progress.

Fortran has won a place in the field of numerical and mathematical computing with its excellent performance and mature technology, beating many competitors.

The free and open source feature of Fortran gives it an advantage in cost-effectiveness.

img

Official website address: https://fortran-lang.org/

On Amazon, the number of search results for “Fortran programming” far exceeds that of emerging languages Kotlin and Rust, reflecting the market’s continued interest and demand for Fortran.

Comparative analysis with other languages:

  • Although Python is widely popular, it lacks speed.
  • MATLAB is user-friendly, but expensive.
  • C/C++ fast, but lacks native support for mathematical calculations.
  • R is similar to Python, but slightly less popular and faster.
  • Julia, as a rising star, has great potential, but her maturity still needs time to be verified.
  • Fortran is fast, supports native mathematical calculations, has mature technology, and is completely free. These features have enabled Fortran to steadily advance in the jungle of programming languages.

The revival of Fortran is an indisputable fact. It proves that in the continuous evolution of technology, classics and innovation can coexist, and veterans can also radiate new vitality.

img

Fortran, short for “Formula Translation”, is a high-level programming language originally designed for numerical and scientific computing.

  • ** Origin: ** Fortran language was developed by a team led by John W. Backus of IBM in 1957 and is one of the earliest high-level programming languages.
  • The original design goal of Fortran was to help scientists and engineers write programs for scientific computing more easily.
  • ** Syntax Features: ** Fortran has a concise syntax and direct support for mathematical expressions, which makes it very popular in the fields of science and engineering.
  • ** Compiler: ** Fortran programs are usually translated into machine code through a compiler for execution on a computer.
  • Fortran has undergone multiple standardization and upgrades, including Fortran IV, Fortran 66, Fortran 77, Fortran 90, Fortran 95, Fortran 2003, Fortran 2008, and the latest version of Fortran 2018.
  • Parallel computing: Fortran 90 and later versions have added support for parallel computing, maintaining its importance in the high-performance computing (HPC) field.
  • Fortran has a wide range of applications in scientific computing, engineering simulation, numerical analysis, weather forecasting, quantum physics simulation and other fields.
  • ** Cross-platform: ** Fortran compiler supports a wide range of operating systems, including Windows, Linux and macOS.

This month, the top ten rankings are:

# Python,C,C++,Java,C#,JavaScript,Visual Basic,Go,SQL,Fortran

img

# Python,C,C++,Java,C#,JavaScript,Visual Basic,Go,SQL, Fortran historical change curve:

img

Ranked 11-20 programming languages, PHP fell to 16, up one place from last month :

img

Programming languages ranked 21-50:

img

51-100 programming languages:

ABC, ActionScript, Algol, Apex, APL, bc, Boo, Carbon, CIL, CL (OS/400), CLIPS, Clojure, Common Lisp, Curl, DiBOL, Erlang, Factor, Groovy, Hack, Icon, Inform, Io, J, JScript, Ladder Logic, Lingo, LiveCode, LPC, MQL5, NATURAL, Nim, OCaml, OpenEdge ABL, Oxygene, Paradox, PL/I, PowerShell, Pure Data, Q, Ring, RPG, Scheme, Smalltalk, SPARK, Standard ML, WebAssembly, Wolfram, X++, Xojo, XPL

Historical rankings of major programming languages (1988-2024):

img

Programming Language “Celebrity List” (2003-2023):

img

TIOBE publishes a monthly ranking of programming languages based on the number of global technical engineers, courses, and third-party suppliers, including popular search engines and technical communities such as Google, Baidu, Wikipedia, Lingo, etc.

The data reflects the changing trend of mainstream programming languages, which can serve as a reference for our learning and work. However, each language has its own suitable application scenarios, so there is no need to pay too much attention to it. After all, the quality of a language depends on how it is used.

The following video shows the changing trends of programming languages in the past 20 years.

Reference: https://www.tiobe.com/tiobe-index/